Here is my code, it takes 2 input parameters, and asks the user to re-input until the input isn’t 1 or 2.
def inputParams(x,y):
while True:
try:
x = int(input(y))
if x == 1 or x == 2:
return x
else:
print("Invalid Input")
inputParams(x, y)
except ValueError:
pass
It works perfectly fine, but as I have heard using
try:
something()
except:
pass
is a bad habit, I want to know if there is an alternative solution to this.
>Solution :
Skip the recursion, and use the ValueError to continue the loop before checking the integer value.
def inputParam(prompt):
while True:
x = input(prompt)
try:
n = int(x)
except ValueError:
print("Invalid integer input")
continue
if n == 1 or n == 2:
return n
print("Enter 1 or 2")