Skip to content
PythonControl Flowbeginner18 min read

while Loops

Learn how while loops repeat code while a condition is true, how to update loop variables, and how to avoid infinite loops.

In this lesson, you will learn

  • ✓Explain how a while loop checks a condition before each iteration.
  • ✓Trace changes to a loop variable and predict the exact output.
  • ✓Write while loops that terminate by updating their state.
  • ✓Recognize infinite loops and explain how to prevent them.
  • ✓Use while loops for condition-controlled repetition.
  • ✓Choose between a for loop and a while loop for a simple programming task.

1. What Is a while Loop?

A while loop repeats a block of code while a specified condition evaluates to True. Python checks the condition before every iteration. If the condition is True, Python executes the indented loop body. When the body finishes, Python checks the condition again.

If the condition is False before the first iteration, the loop body does not execute at all. If the condition becomes False after an iteration, Python exits the loop and continues with the first statement after it.

The general syntax is:

while condition:

# Statements to repeat

The colon is required, and the loop body must be indented. The condition is an expression that evaluates to True or False. A loop variable is often used to make progress toward a stopping condition, although the condition may also depend on other program state.

A while loop does not automatically change its variables. If the loop condition depends on a variable that never changes, the loop may never end.

Count down from 3

Count down from 3
python
count = 3
 
while count > 0:
print(count)
count -= 1
 
print("Go")
Output
3 2 1 Go

The variable count starts at 3. Python checks count > 0. Because 3 > 0 is True, it executes the loop body and prints 3. The statement count -= 1 subtracts 1 from count. The value becomes 2. The same process repeats for 2 and 1. After count becomes 0, the condition 0 > 0 is False, so the loop ends. The final print("Go") is outside the loop and executes once after the loop finishes.

2. How a while Loop Executes

To understand a while loop, trace three things: the condition, the loop variable, and the statements inside the body. The condition is checked first; the body runs only when the condition is True.

Consider a loop that starts n at 1 and continues while n is less than 4. The statement n += 1 increases n by 1 during every iteration. That update eventually makes the condition False.

The operators used in the condition matter. For example, n < 4 means n must be strictly less than 4. The value 4 does not satisfy that condition.

Print numbers from 1 to 3

Print numbers from 1 to 3
python
n = 1
 
while n < 4:
print(n)
n += 1
Output
1 2 3

Initially, n is 1. The condition 1 < 4 is True, so Python prints 1 and changes n to 2. The next check is 2 < 4. It is True, so Python prints 2 and changes n to 3. The next check is 3 < 4. It is True, so Python prints 3 and changes n to 4. The next check is 4 < 4. It is False, so the loop ends. The number 4 is not printed because the condition is checked before the body executes.

Note

A condition is not checked just once. Python checks it before every iteration, including the check that eventually ends the loop.

3. Updating Variables and Avoiding Infinite Loops

Many while loops use a variable to track progress. The loop body must update the relevant state so that the condition can eventually become False.

An infinite loop is a loop that continues indefinitely unless something outside the normal condition stops it, such as an interruption or a break statement. One common cause is forgetting to update the variable used in the condition.

For example, if count starts at 1 and the condition is count <= 3, but count never changes inside the loop, the condition remains True. The loop keeps printing 1 and does not reach the statement after the loop under normal execution.

Not every while loop needs a numeric counter. A loop can also depend on user input, a changing status, or another condition. In those cases, make sure the body or another part of the program can update the state that controls the condition.

Correctly update a counter

Correctly update a counter
python
count = 1
 
while count <= 3:
print(count)
count += 1
 
print("Done")
Output
1 2 3 Done

The loop starts with count equal to 1. After printing each value, count increases by 1. When count becomes 4, the condition count <= 3 is False. The loop ends, and Done is printed once.

Caution

Before running a while loop, identify what will make its condition False. If no possible statement or external event can change the relevant state, the loop may run indefinitely.

4. Using while Loops for Condition-Controlled Repetition

A while loop is useful when the number of iterations depends on a condition rather than a predetermined sequence. For example, a program might continue processing values until a sentinel value is entered. A sentinel is a special value that signals the program to stop.

The following example uses a fixed value to demonstrate the same control flow without requiring interactive input. The loop processes each value until it reaches the sentinel value 0.

In a real interactive program, input() returns a string. If you need numeric comparisons, convert the input to an integer or another appropriate type and handle invalid input when necessary. The example below uses an existing list so that its behavior and output are deterministic.

Stop when a sentinel value is reached

Stop when a sentinel value is reached
python
values = [4, 7, 2, 0, 9]
index = 0
 
while values[index] != 0:
print(values[index])
index += 1
 
print("Stopped")
Output
4 7 2 Stopped

The variable index starts at 0, so values[index] refers to the first item, 4. The loop continues while the current item is not 0. The values 4, 7, and 2 are printed as index advances. When index reaches 3, values[index] is 0. The condition is False, so the loop ends without printing 0 or processing the later value 9. Stopped is printed after the loop. This example assumes the list contains a 0 before index reaches the end. Without that guarantee, accessing values[index] could raise IndexError.

Note

When a while loop uses an index to access a list, check the index boundary before accessing the item. A condition such as index < len(values) prevents an attempt to access an index beyond the end of the list.

5. while Loops Compared with for Loops

Both for and while loops repeat code, but they are often used for different kinds of tasks.

A for loop is usually the clearer choice when processing each item in an iterable or iterating over a known range. A while loop is often appropriate when repetition should continue until a condition changes, and the number of iterations is not known in advance.

These are guidelines rather than strict rules. Both loop types can solve many of the same problems. Prefer the loop that expresses the requirement most clearly and makes termination easy to understand.

Use for when the range is known

Use for when the range is known
python
for number in range(1, 4):
print(number)
Output
1 2 3

The range defines the integers to process. Python obtains each integer automatically, so a separate counter update is unnecessary.

6. Common Errors and Edge Cases

The most common while-loop errors involve incorrect conditions, missing updates, and indentation. A loop may execute zero times if its initial condition is False, or repeat indefinitely if its condition never becomes False.

Pay close attention to comparison operators. The conditions count < 3 and count <= 3 are different: the second condition allows the value 3 to enter the loop body.

Also remember that changing a variable inside the loop does not cause Python to skip the next condition check. Python completes the current body, then evaluates the condition again.

Test boundary values such as zero, negative starting values, and values just below or at the stopping threshold. These tests help expose off-by-one errors.

Understand the difference between < and <=

Understand the difference between < and <=
python
count = 1
 
while count < 3:
print(count)
count += 1
 
print("Finished")
Output
1 2 Finished

The loop runs when count is 1 and 2. After the second iteration, count becomes 3. The condition 3 < 3 is False, so 3 is not printed. Using count <= 3 instead would allow one more iteration and print 3.

Caution

Avoid testing a loop that you know cannot terminate unless you can safely interrupt its execution. For ordinary beginner exercises, choose a condition and update that make the stopping point easy to predict.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Forgetting to update the variable that controls the condition.

Why it happens: If the condition variable never changes in a way that can make the condition false, the loop may run indefinitely.

Incorrect Approach
script.py
python
Forgetting to update the variable that controls the condition.
Correct Solution
script.py
python
If the loop relies on a counter, update it inside the body so the condition can eventually become False.

Key takeaway: If the loop relies on a counter, update it inside the body so the condition can eventually become False.

#2 Assuming the condition is checked after the body for the first time.

Why it happens: A while loop checks its condition before entering the body, so a false initial condition means zero iterations.

Incorrect Approach
script.py
python
Assuming the condition is checked after the body for the first time.
Correct Solution
script.py
python
Python checks the condition before every iteration. If it is initially False, the body runs zero times.

Key takeaway: Python checks the condition before every iteration. If it is initially False, the body runs zero times.

#3 Using < when the requirement needs <=, or the reverse.

Why it happens: Boundary operators differ at the exact limit; use < or <= according to whether the limit itself should be included.

Incorrect Approach
script.py
python
Using < when the requirement needs <=, or the reverse.
Correct Solution
script.py
python
Check whether the boundary value should be included. Use < for a strict boundary and <= when equality should also satisfy the condition.

Key takeaway: Check whether the boundary value should be included. Use < for a strict boundary and <= when equality should also satisfy the condition.

#4 Placing a statement outside the loop when it should repeat.

Why it happens: Only statements inside the indented loop body repeat; indentation determines which work is performed each iteration.

Incorrect Approach
script.py
python
Placing a statement outside the loop when it should repeat.
Correct Solution
script.py
python
Indent statements that belong to the loop body. Statements at the outer indentation level run after the loop.

Key takeaway: Indent statements that belong to the loop body. Statements at the outer indentation level run after the loop.

#5 Indenting a final statement inside the loop when it should run only once.

Why it happens: A final statement indented inside the loop repeats, which can print partial results many times instead of one final result.

Incorrect Approach
script.py
python
Indenting a final statement inside the loop when it should run only once.
Correct Solution
script.py
python
Move the statement to the same indentation level as the while statement when it should execute after the loop finishes.

Key takeaway: Move the statement to the same indentation level as the while statement when it should execute after the loop finishes.

#6 Assuming a while loop always executes at least once.

Why it happens: Unlike do-while constructs in some languages, Python's while loop may execute zero times if its initial condition is false.

Incorrect Approach
script.py
python
Assuming a while loop always executes at least once.
Correct Solution
script.py
python
The condition is checked before the first iteration. If it is False initially, the body is skipped.

Key takeaway: The condition is checked before the first iteration. If it is False initially, the body is skipped.

#7 Accessing a list with an index without checking its boundary.

Why it happens: An index can become invalid as a list changes or the index advances, so check its bounds before direct access.

Incorrect Approach
script.py
python
Accessing a list with an index without checking its boundary.
Correct Solution
script.py
python
When the index may reach the end of a list, use a condition such as index < len(values) before accessing values[index].

Key takeaway: When the index may reach the end of a list, use a condition such as index < len(values) before accessing values[index].

#8 Using a while loop when a for loop would express a known sequence more clearly.

Why it happens: When iterating over a known sequence, a for loop is usually clearer; use while when repetition depends on a condition or ongoing state.

Incorrect Approach
script.py
python
Using a while loop when a for loop would express a known sequence more clearly.
Correct Solution
script.py
python
Use for when processing an iterable or known range is the natural fit. Use while when a condition controls whether repetition continues.

Key takeaway: Use for when processing an iterable or known range is the natural fit. Use while when a condition controls whether repetition continues.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is a while loop in Python?
Answer:
A while loop repeatedly executes an indented block as long as its condition evaluates to True. Python checks the condition before each iteration.
Q2:What is an infinite loop, and how can you prevent one?
Answer:
An infinite loop continues indefinitely under normal execution because its stopping condition never becomes False. To prevent accidental infinite loops, identify the stopping condition and ensure the loop body or another part of the program can update the state needed to reach it.
Q3:What happens if the condition is False before the first iteration?
Answer:
The loop body executes zero times. Python continues with the first statement after the loop.
Q4:What is the difference between for and while loops?
Answer:
A for loop processes items from an iterable, such as a list, string, or range. A while loop repeats while a condition is True. A for loop is often clearer for processing a known sequence, while a while loop is useful when repetition depends on a changing condition.
Q5:Why is updating a loop variable important?
Answer:
When a condition depends on a variable, updating that variable may allow the condition to become False. If the relevant state never changes, the loop may run indefinitely.
Q6:How can a while loop safely traverse a list using an index?
Answer:
Initialize index to 0 and continue while index < len(values). Access values[index] inside the loop and increment index during each iteration. This stops the loop before the index reaches len(values).
Q7:How do you debug an unexpected while-loop result?
Answer:
Trace the initial variable values, evaluate the condition before every iteration, record the statements executed, and update the variables after each iteration. Check boundary operators and verify that the stopping condition is eventually reached.

Key takeaways

  • A while loop repeats its body while its condition evaluates to True.
  • Python checks the condition before every iteration, including the first.
  • If the condition is initially False, the loop body executes zero times.
  • Update the state that controls the condition so the loop can terminate when intended.
  • An infinite loop can occur when its condition never becomes False.
  • The difference between < and <= affects whether a boundary value is included.
  • When using an index to traverse a list, check index < len(values) before accessing an item.
  • Use for loops for clear iteration over known sequences and while loops when a changing condition controls repetition.
  • Dry runs help you track conditions, variable updates, and exact output.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: