How to validate input using if and else

How to validate input using if and else

Problem Description:

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 themn")
    print(val_1, "is the first number and", val_2, "is the second numbern")
    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 numbern")
            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.

Solution – 1

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  
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject