In this tutorial, you’ll learn what a while loop is in Python and how to use it. A while loop repeats a block of code as long as a condition stays true. It is the right choice when you don’t know in advance how many times the code needs to run.
By the end of this article, you’ll know how to write while loops, avoid infinite loops, control them with break, continue, pass, and else, and use common patterns such as input validation and while True loops.
Also, Solve:
Table of contents
- What is a while loop in Python?
- Why and when to use a while loop in Python
- Infinite while loop
- If-else in a while loop
- Transfer statements in a while loop
- Nested while loops
- Else statement in a while loop
- Reverse while loop
- Iterate a string using a while loop
- Iterate a list using a while loop
- while loop with the walrus operator
- Common mistakes and best practices
- Summary
- Next Steps
What is a while loop in Python?
In Python, the while loop statement repeatedly executes a block of code as long as a given condition is true.
In simple words, a while loop lets your program repeat a set of operations while a condition is true. As soon as the condition becomes false, the loop stops, and Python runs the first statement after the loop.
The while loop is one of Python’s control flow statements, and understanding it is an essential part of learning the basics of Python.
Use a while loop when the number of iterations is not known beforehand. For example, if you ask a user to guess your lucky number between 1 and 10, you don’t know how many attempts they will need. A while loop can keep asking until they get it right.
- Indefinite iteration: The number of iterations is unknown. For example, asking the user to guess a lucky number. It could take 1 attempt, 20, or more. In such cases, use a
whileloop. - Definite iteration: The number of iterations is fixed. For example, printing the multiplication table of 2 needs exactly 10 iterations. In such cases, use a for loop.

Syntax of a while loop
while condition:
# block of statement(s)Code language: Python (python)
- The
whilestatement first checks thecondition. The condition is any expression that Python can evaluate asTrueorFalse. - If the condition is
True, Python runs the indented statements inside the loop body. - After the body finishes, Python checks the condition again. This repeats until the condition becomes
False. - If the condition is
Falsethe very first time, the loop body never runs at all. - Don’t forget the colon (
:) after the condition, and indent the loop body (usually by 4 spaces).
Example of a while loop in Python
Let’s start with a simple example.
Example 1: Print numbers less than 5
Output:
1 2 3 4
In this example, the loop runs as long as the count variable is less than 5. In each iteration, we increase count by 1. When count reaches 5, the condition becomes false and the loop stops.
Note: If you forget to increase count in the example above, the condition will always be true and the loop will run forever.
Example 2: Count how many times a number must be divided by 3 until it is less than or equal to 10
Here, the number of iterations depends on the starting number, so we can’t know it in advance. This is exactly the kind of problem a while loop is made for.
Output:
Total iterations required: 3
The number goes from 180 to 60, then 20, then about 6.67. After the third division, it is no longer greater than 10, so the loop stops.
Flowchart of a while loop

Why and when to use a while loop in Python
Here are the main reasons to choose a while loop:
- Automate and repeat tasks: A
whileloop runs a block of code again and again until its condition is no longer met, so you can automate repetitive work efficiently. - Indefinite iteration: The loop runs as many times as needed to finish the task. When you don’t know the number of iterations before the program runs, use a
whileloop instead of aforloop. - Less repetitive code: Instead of writing the same statements many times, you write them once inside the loop body. This keeps the code short and easy to maintain.
- Wait for an event: A
whileloop can keep running until something happens, such as the user typing “quit”, a file becoming available, or a game ending.
Example: Make sure the user enters valid input
In this example, we want the user to enter a number between 100 and 500. We keep asking until they enter a number within that range.
Output:
Enter any number between 100 and 500: 700 Incorrect number. Please try again. Enter a number between 100 and 500: 98 Incorrect number. Please try again. Enter a number between 100 and 500: 300 The given number is correct: 300
while loop vs for loop
- for loop: Loops over the items of a sequence or a
range(). Use it when you know how many times to repeat, or when you want to process every item in a collection. - while loop: Loops as long as a condition is true. Use it when the number of repetitions depends on something that changes while the program runs, such as user input or a calculation result.
- In a
forloop, Python moves to the next item for you. In awhileloop, you are responsible for changing something so that the condition eventually becomes false.
Infinite while loop
If the condition of a while loop never becomes false, the loop runs forever. This is called an infinite loop.
# Infinite while loop
while True:
print('Hello')Code language: Python (python)
An accidental infinite loop is a bug, usually caused by forgetting to update the loop variable. If your program gets stuck, press Ctrl + C in the terminal to stop it (this raises a KeyboardInterrupt).
while True with break
Infinite loops can also be intentional. A very common pattern is while True combined with a break statement that exits the loop when a certain condition is met. Programs such as menus, chat bots, and games often work this way.
Output:
Type something (or 'quit' to exit): hello You typed: hello Type something (or 'quit' to exit): python You typed: python Type something (or 'quit' to exit): quit Goodbye!
Emulating a do-while loop
Some languages have a do-while loop, which always runs its body at least once and checks the condition at the end. Python doesn’t have a do-while loop, but you can get the same behavior with while True and a break at the bottom of the loop.
Output:
x is 10
Even though x is already greater than 3, the body runs once before the condition is checked.
If-else in a while loop
If-else statements let you run different blocks of code depending on whether a condition is true or false.
Use an if-else statement inside a loop when you want to do different things in different iterations. If the condition is True, the statements inside the if block run. Otherwise, the else block runs.
Syntax of an if-else statement
if condition:
block of statements
else:
block of statementsCode language: Python (python)
Example: Print even and odd numbers from the entered number down to 1
Output:
Please enter a number: 7 7 is an odd number 6 is an even number 5 is an odd number 4 is an even number 3 is an odd number 2 is an even number 1 is an odd number
Transfer statements in a while loop
Loop control statements change the normal flow of a loop. Use them when you want to exit a loop early or skip part of it based on a condition. They are also known as transfer statements.
Python has three loop control statements: break, continue, and pass.
Break statement
The break statement ends the loop that contains it immediately. If you use break inside a nested loop (a loop inside another loop), it ends only the innermost loop.
Example: Display each character of a string and stop the loop when a digit is found
Output:
J e s s a
Continue statement
The continue statement skips the rest of the loop body for the current iteration and jumps back to the condition check. Unlike break, it doesn’t end the loop.
Example: Display only the letters of a string
In this example, we print only the letters and skip all digits and special symbols. Notice that we increase i before the continue statement. If the increment came after continue, it would be skipped and the loop would never end.
Output:
J e s s a R o y
Pass statement
The pass statement is a null statement: nothing happens when it runs. Python doesn’t allow an empty block, so pass works as a placeholder when the syntax needs a statement but you have nothing to write yet. It is also commonly used in empty functions and classes.
Nested while loops
A while loop inside another while loop is called a nested loop.
For each iteration of the outer loop, the inner loop runs through all of its iterations. So the total number of iterations is the outer loop’s iterations multiplied by the inner loop’s iterations.
while expression:
while expression:
statement(s) of inner loop
statement(s) of outer loopCode language: Python (python)
Example: Use a nested while loop to print a pattern
* * * * * * * * * *
Note that the inner counter j is reset to 0 at the start of every outer iteration. Forgetting this reset is a common mistake with nested while loops.
for loop inside a while loop
You can also use a for loop inside a while loop. Here is the same pattern written with an inner for loop, which removes the need for the j counter:
Else statement in a while loop
A while loop can have an optional else block. The else block runs once, when the loop condition becomes false, that is, when the loop ends normally.
The else block does not run when the loop is stopped by a break statement (or by an exception or a return).
Example 1: Use a while loop to print numbers from 1 to 5
Output:
1 2 3 4 5 Done. while loop executed normally
Example 2: Else block with a break statement
Here the loop is stopped by break when i equals 3, so the else block is skipped.
Output:
1 2 3
Example 3: A practical use of while-else: searching for an item
Find the first multiple of 5 in a list. If none is found, the else block reports it, with no extra flag variable needed.
Output:
First multiple of 5: 15
Reverse while loop
A reverse loop iterates backward. Common examples are:
- Displaying numbers from 10 down to 1
- Reversing a string or a list
Example: Use a reverse while loop to display numbers from 10 to 1
Output:
10 9 8 7 6 5 4 3 2 1
Iterate a string using a while loop
You can loop through a string with a while loop by using an index variable that goes from 0 to len(string) - 1.
Example 1: Iterate a string letter by letter
Output:
J e s s a
Example 2: Iterate a string in reverse order
Output:
a s s e J
Iterate a list using a while loop
A Python list is an ordered sequence of items. Each item has an index number, starting from 0. Lists are written inside square brackets []. Here are some examples of lists:
numbers = [1, 2, 4, 6, 7]
names = ["Messi", "Ronaldo", "Neymar"]Code language: Python (python)
Example 1: Use a while loop to iterate over a list
Output:
1
2
4
5
7
Example 2: Process a list until it is empty
An empty list is treated as False in a condition, so while tasks: keeps running as long as the list has items. The pop() method removes and returns the last item, so the list shrinks in each iteration.
Output:
Doing: review Doing: code Doing: email Tasks left: []
Tip: To simply visit every item of a list, a for loop is shorter and safer. Use a while loop when the list changes inside the loop or when you need to stop based on a condition.
while loop with the walrus operator
Python 3.8 introduced the assignment expression operator :=, nicknamed the walrus operator. It lets you assign a value and test it in the same while condition, which avoids repeating the same line before and inside the loop.
Output:
Enter text: a Read: a Enter text: b Read: b Enter text:
Common mistakes and best practices
- Forgetting to update the loop variable: This is the most common cause of infinite loops. Make sure something in the loop body moves the condition toward
False. - Skipping the update with
continue: If the increment comes after acontinuestatement, it may never run. Update the counter beforecontinue. - Off-by-one errors: Check whether you need
<or<=. For example,while i < 5stops at 4, whilewhile i <= 5includes 5. - Not resetting the inner counter: In nested
whileloops, reset the inner counter at the start of each outer iteration. - Using a while loop where a for loop is clearer: To visit every item in a list or repeat something a fixed number of times, a
forloop is shorter and less error-prone. - Floating-point conditions: Avoid conditions like
while x != 1.0with floats. Rounding errors may stopxfrom ever exactly matching. Use<or>instead.
Summary
- A
whileloop repeats a block of code as long as its condition isTrue. - Use it when you don’t know in advance how many iterations you need. Use a
forloop when you do. - Always change something inside the loop so the condition eventually becomes
False, or the loop will run forever. while Truewithbreakis a common pattern for menus, input loops, and do-while behavior.breakexits the loop,continueskips to the next iteration, andpassdoes nothing.- The optional
elseblock runs only when the loop ends withoutbreak. - The walrus operator
:=lets you assign and test a value in the loop condition.
Next Steps
Practice what you’ve learned, and continue with the related tutorials on for loops, nested loops, and break, continue, and pass.
