Back to: Python Programming
- Python while loop is used to repeat a block of code until the specified condition is False.
- The while loop is used when we don’t know the number of times the code block has to execute.
- We should take proper care in writing while loop condition if the condition never returns False, the while loop will go into the infinite loop.
- Every object in Python has a boolean value. If the value is 0 or None, then the boolean value is False. Otherwise, the boolean value is True.
- We can define an object boolean value by implementing
__bool__()function. - We use the reserved keyword – while – to implement the while loop in Python.
- We can terminate the while loop using the break statement.
- We can use continue statement inside while loop to skip the code block execution.
- Python supports nested while loops.
A “while loop” will execute WHILE some condition remains true. They are used to repeat a specific block of code an unknown number of times, until a condition is met.

If we want to ask a user for their name then address them by their name, we should check for a valid input. If they do NOT enter their name, our code should keep asking until the user enters something.
name = input("What is your name? ")
while name == "":
print("You did NOT enter your name")
name = input("What is your name? ")
print(f"Hello, {name}!")
This code will ask for a name indefinitely until one is provided.
A similar example for an age range:
age = int(input("What is your age? "))
while age < 0 or age > 120:
print("You did NOT enter a valid age. Try again.")
age = int(input("What is your age? "))
print(f"You are {age}!")
If we want to keep asking questions and give the user the opportunity to Quit:
song = input("Enter a song you really like (press q to quit): ")
while not song == "q":
print(f"You like the song {song}")
song = input("Enter another song (q to quit): ")
print("Thank you for the chat, cya!")
Exercise:
Ask the user to enter a number between 1 and 10. If they type a wrong number, ask again and keep asking until they enter a valid response.
while loop with multiple false strings
Here’s how to handle multiple string conditions that should result in a False evaluation to terminate a while loop in Python:
To correctly evaluate multiple string conditions for exiting a while loop, you need to ensure each condition is explicitly checked. A common mistake is to use the or operator incorrectly, which can lead to unintended behavior.
Incorrect Usage:
text = "start"
while text != "stop" or "pause" or "quit":
print("Looping")
text = input("Enter command: ")
print("Stopped")
In the above example, the condition text != "stop" or "pause" or "quit" will always evaluate to True. This is because "pause" and "quit" are non-empty strings, which are truthy in Python. Thus, the loop will never terminate as intended.
Correct Usage
There are two primary ways to correctly handle multiple string conditions in a while loop: Using the and operator.
text = "start"
while text != "stop" and text != "pause" and text != "quit":
print("Looping")
text = input("Enter command: ")
print("Stopped")
This approach ensures that the loop continues only if all the conditions are true. If text is equal to “stop”, “pause”, or “quit”, the loop will terminate.
- Using the
not inoperator with a list or tuple:
text = "start"
while text not in ["stop", "pause", "quit"]:
print("Looping")
text = input("Enter command: ")
print("Stopped")
This method checks if text is not present in the given list or tuple. If it is, the loop terminates. This approach is cleaner and more readable, especially when dealing with numerous conditions.
while Loop with break Statement
Sometimes we explicitly want to execute a code block indefinitely until the exit signal is received. We can implement this feature using “while True” block and break statement.
Here is an example of a utility script that takes the user input (integer) and prints its square value. The program terminates when the user enters 0.
while True:
i = input('Please enter an integer (0 to exit):\n')
i = int(i)
if i == 0:
print("Exiting the Program")
break
print(f'{i} square is {i ** 2}')
Python while Loop with continue Statement
Let’s say we want the above script to work with positive numbers only. In that case, we can use continue statement to skip the execution when user enters a negative number.
while True:
i = input('Please enter an integer (0 to exit):\n')
i = int(i)
if i < 0:
print("The program works with Positive Integers only.")
continue
if i == 0:
print("Exiting the Program")
break
print(f'{i} square is {i ** 2}')
Outputs:
Please enter an integer (0 to exit):
5
5 square is 25
Please enter an integer (0 to exit):
-10
The program works with Positive Integers only.
Please enter an integer (0 to exit):
0
Exiting the Program
Python while Loop with else Statement
If the while loop terminates because of Error or break statement, the else block code is not executed.
We can use else block with the while loop. The else block code gets executed when the while loop terminates normally i.e. the condition becomes False.
If the while loop terminates because of Error or break statement, the else block code is not executed.
count = 5
while count > 0:
print("Welcome")
count -= 1
else:
print("Exiting the while Loop")
Let’s see what happens when the while loop terminates because of an error.
count = 5
while count > 0:
print("Welcome")
count -= 1
if count == 2:
raise ValueError
else:
print("Exiting the while Loop")
Let’s change the program to break out of the while loop.
count = 5
while count > 0:
print("Welcome")
count -= 1
if count == 2:
break
else:
print("Exiting the while Loop")