Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to have a yes/no loop in my code, but I'm having trouble doing it (python 3.3)

Tags:

python

loops

Sorry I'm just a beginner at python so this is probably a very simple question, but I have a code and I want to loop it so after the code asks the user if they want to play again and the user inputs 'yes' to restart the code and 'no' to end the code. If they input anything other than yes or no it should ask tell them to enter yes or no then ask the question again. How would I do this exactly? (I do know about while and for loops but I'm not sure how I would use them in this way)

like image 204
user3412375 Avatar asked Oct 22 '25 22:10

user3412375


2 Answers

This is a simple one:

while True:
    a = input("Enter yes/no to continue")
    if a=="yes":
        gameplay()
        continue
    elif a=="no":
        break
    else:
        print("Enter either yes/no")

Where gameplay function contains the code to be executed

like image 165
Aswin Murugesh Avatar answered Oct 25 '25 11:10

Aswin Murugesh


I would do it the following way:

while True:
    # your code
    cont = raw_input("Another one? yes/no > ")
    while cont.lower() not in ("yes","no"):
        cont = raw_input("Another one? yes/no > ")
    if cont == "no":
        break

If you use Python3 change raw_input to input.

like image 44
halex Avatar answered Oct 25 '25 11:10

halex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!