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

Question:

def input_params():
    user_input = int(input("Input a number"))
    while user_input != 1 or user_input != 2:
        try:
            user_input = int(input("Input a number"))
            if user_input == 1 or user_input == 2:
                return user_input
            else:
                print("Invalid Input")
                input_params()
        except ValueError: 
            input_params()

When entering an invalid input such as "adf", and then proceeding to enter a valid input such as 2, the program doesn’t process the valid input and asks me to input a value again. The program only comes to process the valid input on the second time I input it.

Asked By: Illusioner_

||

Answers:

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)

Answered By: The Thonnu

The problem you’re seeing comes from your test. Let’s isolate it:

def f(x):
    return x != 1 or x != 2

Presumably this should return True if x is not 1 or 2. Let’s try it:

def test():
    assert f(0)
    assert not f(1)
    assert not f(2)
    assert f(3)

test() # oops!

Take another look at that test: x != 1 evaluates to True unless x is 1. x != 2 evaluates to True unless x is 2. If x is 2, the first test is True. If x is 1, the second test is True. Thus the code is actually running:

while True: ...

Then later on you check whether x is 1 or 2. A better test would be if x in {1, 2} or even if 1 <= x <= 2.

Then your recursion is muddling things even further, but you don’t actually need recursion for this problem.

Answered By: 2e0byo
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.