PixelCardist
PixelCardist

Reputation: 47

Restart if loop if invalid answer

I have the following code and if the else is triggered, how do I continue to let them input again instead of it exiting the loop?

Tried some while True stuff but couldn't get it to work.

if awaken in ["a", "stand up"]:
    print("Holy...")
elif awaken in ["b", "take a breath"]:
    print("Just more text holding")
elif awaken in ["c", "go back to sleep"]:
    print("")
else:
    print("I don't understand your answer... try again")

Upvotes: 1

Views: 579

Answers (1)

Bilesh Ganguly
Bilesh Ganguly

Reputation: 4131

Put it all inside a while loop.

while True:
    awaken = input("Enter command: ").strip()  # I presume that you are taking input from user
    if awaken in ["a", "stand up"]:
        print("Holy...")
        break
    elif awaken in ["b", "take a breath"]:
        print("Just more text holding")
        break
    elif awaken in ["c", "go back to sleep"]:
        print("")
        break
    else:
        print("I don't understand your answer... try again")

Output:

Enter command: x
I don't understand your answer... try again
Enter command: y
I don't understand your answer... try again
Enter command: a
Holy...

Don't forget to use break.

I'm not sure why yours didn't work initially but the above loop should do the job.

Upvotes: 1

Related Questions