Skip to content

While loop yes or no Python | Example code

  • by

Use while true with if statement and break statement to create While loop yes or no in Python. Simple if while condition equal to “N” then wait for the user input of Y before exiting.

Example While loop yes or no in Python

Simple example code using 2 while loops. If the user inputs the value “no” then break the loops.

while True:
    # your code
    cont = input("Another one? yes/no > ")

    while cont.lower() not in ("yes", "no"):
        cont = input("Another one? yes/no > ")

    if cont == "no":
        print("Break")
        break

Output:

While loop yes or no Python

More examples

While loop in python for do you want to continue.

while True:
    # some code here
    if input('Do You Want To Continue? ') != 'y':
        break

Output:

Do You Want To Continue? y
Do You Want To Continue? n

OR

while input("Do You Want To Continue? [y/n]: ") == "y":
    # do something
    print("doing something")

Output: Do You Want To Continue? [y/n]: n

Long code with function

Best to keep function definition separate from the loop for clarity. Also, otherwise, it will be read in every loop wasting resources.

def yes_or_no(question):
    reply = str(input(question + ' (y/n): ')).lower().strip()
    if reply[0] == 'y':
        return 1
    elif reply[0] == 'n':
        return 0
    else:
        return yes_or_no("Please Enter (y/n) ")


print("started")
while True:
    # DRAW PLOT HERE;
    print("See plot....")
    if yes_or_no('Do you like the plot'):
        break
print("done")

Output:

started
See plot….
Do you like the plot (y/n): y
done

Loop the question to allow for repeated incorrect input

    answer = None 
    while answer not in ("yes", "no"): 
        answer = input("Enter yes or no: ") 
        if answer == "yes": 
             # Do this. 
        elif answer == "no": 
             # Do that. 
        else: 
        	print("Please enter yes or no.") 

Do comment if you have any doubts or suggestions on this Python while loop code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.