0

I've to create a program that takes 2 random prime numbers between 10,000-20,000 and sum them together. I seem to have gotten this ok, but when I ask if the user wants to generate another set within a loop I cant seem to get the validation working. I wont include the code that figures out the prime number as that is working ok.

val_1 = random.choice(prime_list)
    val_2 = random.choice(prime_list)   
    print("This program will find 2 prime numbers in the specified range and sum them\n")
    print(val_1, "is the first number and", val_2, "is the second number\n")
    print(val_1, "+", val_2, "=", val_1 + val_2)
    
    
    
    #PLAY AGAIN
    while True:
        reset = input("Would you like to generate 2 new numbers? Y/N ").lower()
        
        if reset == "y":
            val_1 = random.choice(prime_list)
            val_2 = random.choice(prime_list)  

            print(val_1, "is the first number and",val_2, "is the second number\n")
            print(val_1, "+", val_2, "=", val_1 + val_2)

            continue
        else:
            print("Goodbye") 
            quit()

Thanks for any help.

What I have tried is using if result != "y" or "n" and it just seems to then loop the question.

DM0909
  • 3
  • 2
  • [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself)! You can put the code once inside the while loop and ask the reset question at the end of it (`break` if answer is not "y"). This way if the code works once, it will likely work always, you don't need to debug it many times. – Ignatius Reilly Dec 06 '22 at 17:07
  • And please fix the indentation in your post. – Ignatius Reilly Dec 06 '22 at 17:08
  • `result != "y" or "n"` won't work because of [this](https://stackoverflow.com/questions/20002503/why-does-a-x-or-y-or-z-always-evaluate-to-true-how-can-i-compare-a-to-al) – Ignatius Reilly Dec 06 '22 at 17:10
  • Quick fix (but I would encourage you to try my comment, is to replace `quit()` by `break` (see suggested duplicate). – Ignatius Reilly Dec 06 '22 at 17:14
  • Does this answer your question? [python quit function not working](https://stackoverflow.com/questions/45354330/python-quit-function-not-working) – Ignatius Reilly Dec 06 '22 at 17:15

1 Answers1

0

If you write if result != "y" or "n":, it is interpreted the same as if (result != "y") or ("n"):. Because the non-empty string "n" evaluates to True, this if statement will always be true. Try something like:

while True:
    reset = input("Would you like to generate 2 new numbers? Y/N ").lower()
    if reset not in {"y", "n"}:
        print("Invalid input")
        continue
    # Process valid input here  
jprebys
  • 2,469
  • 1
  • 11
  • 16