Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiple unnecessary input appearing when using try except handling for input params

I am trying to make a few params for inputs using try/except so that input is repeated until expected input is given

def inputParams(x,y):
    while x != 1 or x != 2:
        try:
            x = int(input(y))
            if x == 1 or x == 2:
                return x
            else:
                print("Invalid Input")
                inputParams(x, y)
        except:
            inputParams(x, y)

My problem is that when i give an invalid input, the try statement asks me to repeat my input, and even though i give a valid input in the repeated input, it asks me to repeat my input the number of times i gave an invalid input.

Image to show what i meanenter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As you can see, the input "ffd" is invalid, so the program asks me to repeat my input, but the input of 1 is valid, but the program asks me to repeat my input again, this issue is resolve however, after entering my input for the second time, but number of time i need to repeat my input corresponds with the number of times i gave an invalid input

>Solution :

You don’t need to use recursion. This code works just fine:

def inputParams(x,y):
    while True:
        try:
            x = int(input(y))
            if x == 1 or x == 2:
                return x
            else:
                print("Invalid Input")
        except:
            pass

If you want to use recursion, delete the while loop, or use return inputParams(x, y) rather than just inputParams(x, y) to exit the function:

def inputParams(x,y):
    try:
        x = int(input(y))
        if x == 1 or x == 2:
            return x
        else:
            print("Invalid Input")
            return inputParams(x, y)
    except:
        return inputParams(x, y)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading