1

I've been facing this problem for a bit now. I know that the 'return' command can't work outside a function, but is there an alternative to this or is there a need to define a new function?:

print("Are you", userage(), "years old?")

userinput = input()
if userinput == "yes":
    print("Ok, lets get on with the program")
elif userinput =="no":
    print("Oh, let's try that again then")
    userage()
else:
    print("please answer yes or no")
    return userinput

Btw, sorry for all the mistakes I make. I'm still a beginner.

SirLad
  • 11
  • 2
  • 5
    Make yourself comfortable with loops, especially the `while loop` in your example. – Jan Jun 20 '20 at 16:08
  • If you want to have a return, you also want to have a function. Why not put your input and checks into one that returns the result? – Klaus D. Jun 20 '20 at 16:10
  • @SirLad See https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response – Thierry Lathuille Jun 20 '20 at 16:10
  • What do you think `return` does? Even if this were in a function, it would simply exit the function, which it would do anyway because it's at the end. You seem to think `return userinput` means "go back to where I defined userinput" but it doesn't. – kindall Jun 20 '20 at 16:21
  • @kindall - SirLad is clear that `return` isn't the right thing but is trying to figure out what to do instead. – tdelaney Jun 20 '20 at 16:32
  • Hi all, OP here. Thank you for the comments you guys gave, it helped me in some ways, and also sorry for some inconvenience. – SirLad Jun 21 '20 at 12:49

1 Answers1

1

You need to use a while loop here:

while (True):
    userinput = input("Are you xxx years old?\n")
    if userinput == "yes":
        print("Ok, lets get on with the program")
        break
    elif userinput == "no":
        print("Oh, let's try that again then")
    else:
        print("please answer yes or no")

The loop will ever only break when someone types in yes.

Jan
  • 42,290
  • 8
  • 54
  • 79