How to utilize return between function

Viewed 57

I was trying to prompt input options and validate the input number. I separated into two different function, how can I make this into one function? Perhaps using return?

Code:

def again(option):
     if option == 1:
          print("one")
     elif option == 2:
          print("two")
     else:
          print("Invalid number !")
          retry = int(input("Retry number: "))
          if retry == 0:
               print("return mainpage")
          else:
               while retry > 3 and retry < 0:
                    retry = int(input("Retry number: "))
                    if retry == 0:
                         print("return mainpage")
               else:          
                    again(retry) 
def test():
     option = int(input("Please enter your choices: "))
     again(option)
test()
1 Answers

It is a bit confusing what you are trying to achieve with your code - but from what I understand, you have two options i.e. 1 and 2 that will stop the function but repeat the input until you get those two numbers from the user. In this case you can utilize the following code:

def again():
option = int(input("Please enter your choices: "))    

while True:
    if option == 1:
        return 'one'
    elif option == 2:
        return 'two'
    else:
        option = int(input("Retry number: "))

print(again())

You want to run a while loop until your condition is satisfied and once you do, you simply break that loop. Since we are returning a value, you want to use the print statement to see that answer in your terminal.

Related