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.
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)
