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
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
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
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
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
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
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
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
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 <=
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is a while loop in Python?
Q2:What is an infinite loop, and how can you prevent one?
Q3:What happens if the condition is False before the first iteration?
Q4:What is the difference between for and while loops?
Q5:Why is updating a loop variable important?
Q6:How can a while loop safely traverse a list using an index?
Q7:How do you debug an unexpected while-loop result?
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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: