SECTION 1
Historical Context & Motivation
Long before Python existed, early computer scientists faced a fundamental challenge: how do you instruct a machine to repeat a task without writing the same instructions over and over? Imagine you needed a computer to add up a thousand numbers. Writing one thousand separate addition statements would be absurd. The concept of a loop — a structure that repeats a block of code — became one of the most important ideas in all of programming.
1843 • Ada Lovelace's Notes
1949 • Assembly Language Jumps
1964 • BASIC Introduces WHILE
1991 • Python Is Born
The core question that loops answer is simple yet powerful: How can we make a computer repeat an action as many times as needed without knowing the exact count in advance? A while loop solves this by checking a condition before each repetition and stopping only when that condition becomes false. This section explores how that idea evolved into the Python syntax you will learn today.
SECTION 2
Core Principles & Definitions
A while loop tells Python to keep executing a block of code as long as a given Boolean condition evaluates to True. The moment that condition becomes False, Python exits the loop and continues with the code that follows it. Understanding a few foundational ideas will help you write while loops correctly and confidently.
The Condition
True, the loop body runs. If False, the loop ends.The Loop Body
while statement. This is the set of instructions that repeats with each iteration.The Update Step
False, causing an infinite loop.Iteration
Infinite Loop
False. The program runs forever (or until you force-quit it). This is almost always a bug.KEY TAKEAWAY
True — "still red"). You keep checking: still red? Still red? The moment the light turns green (the condition becomes False — "no longer red"), you proceed. If the light never changes, you're stuck forever — that's an infinite loop.SECTION 3
Visual Explanation — The While Loop Flowchart
Follow the arrows in the diagram above to trace how Python executes this loop. It starts by setting count = 0. Then it reaches the diamond and asks: is count < 5? Since 0 is less than 5, the answer is True, so it enters the body, prints the current value of count, and increments count by 1. The dashed purple arrow sends execution back up to the condition. This cycle repeats for count values 0, 1, 2, 3, and 4. When count reaches 5, the condition is False, and the pink arrow leads to the END.
SECTION 4
How While Loops Work — Syntax & Mechanics
Basic Syntax
Every while loop in Python follows a predictable template. You write the keyword while, followed by a Boolean condition, followed by a colon. The indented lines beneath form the loop body. Python re-evaluates the condition before every iteration.
WHILE LOOP TEMPLATE
condition — a Boolean expression (e.g., x < 10); body — the code that executes each iteration; update — a line that modifies a variable so the condition eventually becomes False.
Counting Iterations
You can often predict how many times a while loop will run by reasoning about the condition and the update step. If a variable starts at value start, increases by step each iteration, and the loop runs while the variable is less than limit, then the number of iterations equals:
ITERATION COUNT
This formula works when step divides evenly into (limit − start). For example, starting at 0, going up by 1, stopping before 5 gives (5 − 0) ÷ 1 = 5 iterations.
The break and continue Statements
Python provides two special keywords for additional loop control. The break statement immediately exits the loop, regardless of the condition. The continue statement skips the rest of the current iteration and jumps back to the condition check. Use these sparingly — most loops can be written clearly with just the condition and update step.
Common Pattern: Sentinel Loop
while user_input != 'quit': keeps asking for input until the user types 'quit'. The word 'quit' acts as the sentinel value — a predetermined signal that means "stop."SECTION 5
Avoiding Infinite Loops & Common Mistakes
The most dangerous mistake when writing a while loop is creating an infinite loop — a loop that never stops because its condition never becomes False. Your program will freeze, consume memory, and you will need to force-quit it (usually with Ctrl+C in the terminal). Learning to identify and prevent infinite loops is just as important as knowing how to write loops.
x += 1) that moves x toward the exit condition. The right panel is missing the update, so x stays at 1 forever.Infinite Loop Prevention Checklist
- ✓ Does the loop body change a variable in the condition? If no variable used in the condition is modified inside the loop, the condition can never change.
- ✓ Is the update moving in the right direction? If your condition is
x < 10but you're subtracting fromx, it will go further from 10, not closer. - ✓ Is the condition using the correct comparison operator? Accidentally writing
!=instead of<can cause the loop to skip past the exit value and loop forever. - ✓ Did you test with a trace table? Walk through 3–4 iterations by hand, writing down each variable's value. Confirm the condition eventually becomes
False.
Emergency Exit
SECTION 6
Worked Example — Sum Until Target
Let's work through a complete while loop program step by step. The goal is to write a program that asks the user for numbers one at a time and adds them up. The loop should stop when the running total reaches or exceeds 100, then display the final sum.
Sum Until the Total Reaches 100
- 1
Step 1 — Initialize Variables
Before the loop begins, we need a variable to hold the running total. Settotal = 0. This variable will appear in the loop's condition and will be updated inside the body.total = 0 - 2
Step 2 — Write the Condition
We want to keep looping as long as the total is less than 100. The condition istotal < 100. Whentotalreaches 100 or more, the condition becomesFalseand the loop ends.while total < 100: - 3
Step 3 — Write the Loop Body
Inside the loop, prompt the user for a number usinginput()and convert it to an integer withint(). Store the result in a variable callednum.num = int(input("Enter a number: ")) - 4
Step 4 — Update the Condition Variable
Add the user's number tototal. This is the critical update step — without it,totalwould stay at 0 forever and the loop would never end.total += num - 5
Step 5 — Display Results After the Loop
After the loop exits (whentotal >= 100), print the final total. This line is not indented under the while statement, so it runs only once, after the loop is done.print("Final total:", total)
The complete program looks like this:
COMPLETE PROGRAM
If the user enters 30, 25, 20, and 30 (totaling 105), the loop runs 4 times and prints Final total: 105.
SECTION 7
While Loops vs. For Loops — When to Use Which
Python has two main loop structures: while loops and for loops. Both repeat code, but they shine in different situations. Understanding their strengths helps you pick the right tool for each task.
| Feature | While Loop | For Loop |
|---|---|---|
| Best when... | You don't know in advance how many iterations you need. | You know exactly how many iterations you need, or you're iterating over a collection. |
| Condition | Any Boolean expression you write. | Automatically managed — iterates over each item in a sequence. |
| Risk of infinite loop | Yes — if update step is missing or wrong. | No — always terminates when the sequence ends. |
| Example use case | Asking for user input until they type 'quit'. | Printing every item in a list. |
| Update responsibility | Programmer must manually update the variable. | Python automatically advances to the next item. |
While loops vs. for loops comparison
KEY TAKEAWAY
SECTION 8
Connection to Advanced Concepts
The while loop is a building block for many powerful programming techniques you will encounter as you progress. Understanding it deeply now will prepare you for recursion, event-driven programming, game loops, and algorithms.
| What You Know Now | What's Coming Next |
|---|---|
| While loop with a counter variable | Nested loops — a loop inside another loop, useful for working with grids and 2D data. |
| Sentinel-controlled loop (stop on special input) | Input validation — using while loops to force users to enter acceptable data before proceeding. |
| Counting iterations | Algorithm efficiency — analyzing how loop count grows with input size (Big O notation). |
| Simple condition check | Event loops & game loops — while loops that run "forever" intentionally, processing user events in real time. |
From while loops to advanced concepts
Interestingly, some advanced programs use while True: loops on purpose — game engines, web servers, and operating systems all rely on loops that run continuously until a break statement or external signal tells them to stop. The key difference between these intentional infinite loops and bugs is that the programmer has planned a clear exit path inside the loop body.
Preview: while True with break
while True: starts a loop that would run forever, but inside the body, an if statement checks a condition and calls break to exit. You'll learn this pattern soon — it's especially useful when the exit condition is checked in the middle of the loop, not at the top.SECTION 9
Practice Problems
Question 1: CONCEPTUAL
Show answer
Question 2: BASIC CALCULATION
n = 10
while n > 0:
print(n)
n -= 3
List every value that is printed, in order.Show answer
Question 3: INTERMEDIATE
even_sum and print it after the loop. How many iterations does your loop perform?Show answer
even_sum = 0
num = 2
while num <= 50:
even_sum += num
num += 2
print(even_sum)
The variable num starts at 2 and increases by 2 each iteration (2, 4, 6, ..., 50). Using the iteration formula: (50 − 2) ÷ 2 + 1 = 25 iterations. The final sum is 650. The loop terminates because num eventually reaches 52, making 52 <= 50 evaluate to False.Question 4: APPLIED
Show answer
attempts = 0
password = ""
while password != "python123" and attempts < 3:
password = input("Enter password: ")
attempts += 1
if password == "python123":
print("Access granted")
else:
print("Account locked")
The condition uses and to require both sub-conditions to be True for the loop to continue. The loop exits either when the password is correct (first condition becomes False) or when 3 attempts have been used (second condition becomes False). After the loop, an if/else determines which message to display.Question 5: CRITICAL THINKING
x = 1
while x != 10:
x += 3
Will this loop terminate? Explain why or why not. Then modify the code with a minimal change so that it terminates safely while keeping the update as x += 3.Show answer
x != 10 to x < 10. With < instead of !=, the loop will exit as soon as x reaches or passes 10, regardless of step size. This is a best practice: prefer < or > over != in loop conditions to avoid accidentally skipping the exit value.SUMMARY
Lesson Summary
Summary
A while loop repeats a block of code as long as a Boolean condition remains True. Every well-written while loop has three essential parts: an initialization that sets the starting value, a condition that controls whether the loop continues, and an update step inside the body that moves the variable toward making the condition False. Forgetting the update step causes an infinite loop — a loop that never ends.
Use while loops when you don't know in advance how many times the code should repeat (e.g., user input, searching for a value). Use for loops when you know the exact number of iterations or are processing items in a collection. Always trace your loops by hand or use a trace table to verify they terminate. Prefer < or > over != in conditions to avoid skipping the exit value. If your loop gets stuck, press Ctrl+C to stop it.