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
While loop in python for do you want to continue.
while True: # some code here if input('Do You Want To Continue? ') != 'y': break
Do You Want To Continue? y
Do You Want To Continue? n
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 == 'y': return 1 elif reply == '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")
Do you like the plot (y/n): y
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 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.