'How can I restart functions on error caused by user input? [duplicate]
I'm coding a big project that has many functions. I want my code to restart functions where errors occur due to user input, to illustrate what I mean I have made this short code:
def myfunction():
UserInput = int(input("Enter 1 or 2"))
if UserInput == 1:
print("hello")
elif UserInput == 2:
print("Bye")
else:
print("Error!, Please choose 1 or 2")
#I want it to restart myfunction()
thanks.
Solution 1:[1]
As @ti7 commented you better use a while loop and not call your function again on error (recursion)
I don't know what you want to do with the input but as I see you do not need to convert it to an integer to check if it's 1 or 2. Because you can get a ValueError if the input is not convertible to integer.
What you'll do, get the input, use a while loop and check if the input is not "1" and "2"
def myfunction():
UserInput = input("Enter 1 or 2")
while UserInput != "1" and UserInput != "2":
UserInput = input("Enter 1 or 2")
if UserInput == "1":
print("hello")
elif UserInput == "2":
print("Bye")
else:
print("Can't be else")
Solution 2:[2]
Simple, just call the function. (You will want the extra UserInput so you can read the text)
def myfunction():
UserInput = int(input("Enter 1 or 2"))
if UserInput == 1:
print("hello")
elif UserInput == 2:
print("Bye")
else:
print("Error!, Please choose 1 or 2")
UserInput = input('Press anything to continue. ')
myfunction()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MSH |
| Solution 2 | ColoredHue |
