The while statement has a conditional expression, and the user enters the String. Just need to use user input in the while statement conditional and evaluate it. If false then Python exits while loop with user input.
Example exit while loop with user input in Python
Simple example code.
flag = "1"
while flag != "0":
print("Not broken")
flag = input("to break loop enter '0': ")
Output:
Another example
Add the movie entered to a list. Continue asking for a movie until the user enters ‘0’. After all, movies have been input, output the list of movies one movie per line.
Use the break keyword to interrupt either a while or a for-loop.
def addMovie():
movies = []
while True:
movie = input("Enter the name of a movie: ")
if movie == "0":
break
else:
movies.append(movie)
print("That's your list")
print(movies)
addMovie()
Output:
Enter the name of a movie: AAA
Enter the name of a movie: BBB
Enter the name of a movie: 0
That’s your list
[‘AAA’, ‘BBB’]
Source: stackoverflow.com
To exit a while loop in Python based on user input, you can use a condition that checks for the desired input from the user. Here’s an example of how you can achieve this:
while True:
user_input = input("Enter 'exit' to quit the loop: ")
if user_input.lower() == 'exit':
break # Exit the while loop
# Do something with the user input or perform other tasks within the loop
print("You entered:", user_input)
# Code continues here after the while loop is exited
print("Loop has been exited.")
In this example, the while True:
creates an infinite loop, meaning the loop will keep executing until the break
statement is encountered. The input()
function takes user input as a string, and the lower()
method is used to convert the input to lowercase, so the loop will exit regardless of whether the user entered ‘exit’, ‘EXIT’, ‘ExIt’, etc.
When the user enters ‘exit’, the break
statement will be executed, and the loop will be exited, allowing the program to continue with the statement after the while loop.
Comment if you have any doubts or suggestions on this Python input function.
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.