Search code examples
pythoninputduplicatestry-catchexcept

try except if two inputs are the same


I currently have a while loop that looks like this:

while True:
    try:
        entry1 = input("input the first number")
        entry2 = input("enter the second number")
        break
    except ValueError:
        print("number must be valid re-enter")

I want to add code that will reprompt the user to enter two different numbers if the user decides to enter two numbers that are the same. I tried using the following:

while True:
    try:
        entry1 = input("input the first number")
        entry2 = input("enter the second number")
        break
    except ValueError:
        print("number must be valid re-enter")
    try: 
        if entry1 == entry2:
            raise ValueError
        else:
            break
    except ValueError as err:
        print("The two numbers cant be the same. re-enter two unique numbers!"

Unfortunately this is not working. Does anyone know what is going wrong with my code?


Solution

  • you can use assert method to make sure the 2 inputs are different and catch with AssertionError if they don't.

    while True:
        try:
            entry1 = int(input("input the first number"))
            entry2 = int(input("enter the second number"))
            assert entry1 != entry2
            break
        except ValueError:
            print("number must be valid re-enter")
        except AssertionError:
            print("The two numbers cant be the same. re-enter two unique numbers!")