Use while true with if statement and break statement to create a While loop yes or no in Python. Simple if while condition equal to “N” then wait for the user input of Y before exiting.
The basic syntax of a while
loop in Python is as follows:
while condition:
# Code block to be executed while the condition is True
# ...
# ...
The condition
is an expression that is evaluated before each iteration of the loop. If the condition is True
, the code block inside the loop will be executed. After each iteration, the condition will be re-evaluated, and the loop will continue as long as the condition remains True
.
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:
More examples
While looping in Python 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 the 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.")
Another example of using a while
loop to ask the user for input and keep asking until they enter “yes” or “no”:
while True:
user_input = input("Enter 'yes' or 'no': ").lower()
if user_input == 'yes':
print("You entered 'yes'.")
break
elif user_input == 'no':
print("You entered 'no'.")
break
else:
print("Invalid input. Please try again.")
In this example, the loop will continue indefinitely until the user enters either “yes” or “no.” The lower()
method is used to convert the user’s input to lowercase, making it case-insensitive. When the user enters “yes” or “no,” the loop will exit using the break
statement.
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.