-1

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.

HumDum
  • 23
  • 6

2 Answers2

1

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()
ColoredHue
  • 59
  • 7
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")
MSH
  • 1,743
  • 2
  • 14
  • 22