Computer Programming 1 (Python) • Control Flow

While Loops — I can write while loops for repetition until a condition changes and avoid infinite loops.

Master the art of telling Python to repeat actions until a specific condition is no longer true.

A Python coding terminal with a program flow and laptop.
Inside this lesson 10 sections 5 questions 7 figures

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

Ada Lovelace described a set of instructions for Charles Babbage's Analytical Engine that included the idea of cycling back to an earlier step — the first recorded concept of a loop in computing.

1949 • Assembly Language Jumps

Early programmers used raw jump instructions (like GOTO) to redirect execution back to previous memory addresses, forming crude loops at the hardware level.

1964 • BASIC Introduces WHILE

High-level languages like BASIC and later Pascal introduced dedicated WHILE keywords, making loops readable and accessible to beginners for the first time.

1991 • Python Is Born

Guido van Rossum released Python, which included a clean and elegant while loop syntax using indentation instead of braces, making loop structures even more intuitive.

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.

1

The Condition

A Boolean expression checked before each iteration. If it evaluates to True, the loop body runs. If False, the loop ends.
2

The Loop Body

The indented block of code beneath the while statement. This is the set of instructions that repeats with each iteration.
3

The Update Step

A statement inside the loop body that changes a variable involved in the condition. Without it, the condition never becomes False, causing an infinite loop.
4

Iteration

A single pass through the loop body. If a while loop runs its body 5 times before stopping, we say it performed 5 iterations.
5

Infinite Loop

A loop whose condition never becomes False. The program runs forever (or until you force-quit it). This is almost always a bug.
✦

KEY TAKEAWAY

Think of a while loop like a traffic light at an intersection. You sit at the red light (the condition is 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

While Loop Execution FlowSTARTcount = 0initializecount < 5 ?(condition)Trueprint(count)bodycount += 1updateloop backFalseEND
This flowchart shows the three essential parts of a while loop: the condition check (diamond), the loop body (green box), and the update step (amber box). The dashed purple arrow shows execution looping back to recheck the condition after each iteration.

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

while<condition>:<body><update>while <condition>: <body> <update>

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

iterations=(limit−start)÷stepiterations = (limit − start) ÷ step

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

A sentinel loop uses a special "signal" value to end input. For example: 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.

Correct Loop vs. Infinite Loop — Side by Side✓ Correct Loopx = 1while x <= 5: print(x) x += 1 ← update!Trace:x=1 → print 1 → x=2x=2 → print 2 → x=3x=3 → print 3 → x=4x=4 → print 4 → x=5x=5 → print 5 → x=6x=6 → 6 <= 5? False → STOP5 iterations, then exits ✓✗ Infinite Loopx = 1while x <= 5: print(x) # no update!Trace:x=1 → print 1 → x still 1x=1 → print 1 → x still 1x=1 → print 1 → x still 1x=1 → print 1 → x still 1... forever and ever ...Never exits! Must force-quit ✗
The left panel shows a correctly written loop with an update step (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 < 10 but you're subtracting from x, 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

If you accidentally create an infinite loop, press Ctrl+C in your terminal to send a keyboard interrupt and stop the program. In some IDEs like IDLE or VS Code, look for a stop or kill button.

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. 1

    Step 1 — Initialize Variables

    Before the loop begins, we need a variable to hold the running total. Set total = 0. This variable will appear in the loop's condition and will be updated inside the body.
    total = 0
  2. 2

    Step 2 — Write the Condition

    We want to keep looping as long as the total is less than 100. The condition is total < 100. When total reaches 100 or more, the condition becomes False and the loop ends.
    while total < 100:
  3. 3

    Step 3 — Write the Loop Body

    Inside the loop, prompt the user for a number using input() and convert it to an integer with int(). Store the result in a variable called num.
    num = int(input("Enter a number: "))
  4. 4

    Step 4 — Update the Condition Variable

    Add the user's number to total. This is the critical update step — without it, total would stay at 0 forever and the loop would never end.
    total += num
  5. 5

    Step 5 — Display Results After the Loop

    After the loop exits (when total >= 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

total=0whiletotal<100:num=int(input("Enteranumber:"))total+=numprint("Finaltotal:",total)total = 0 while total < 100: num = int(input("Enter a number: ")) total += num print("Final total:", total)

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.

FeatureWhile LoopFor 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.
ConditionAny Boolean expression you write.Automatically managed — iterates over each item in a sequence.
Risk of infinite loopYes — if update step is missing or wrong.No — always terminates when the sequence ends.
Example use caseAsking for user input until they type 'quit'.Printing every item in a list.
Update responsibilityProgrammer must manually update the variable.Python automatically advances to the next item.

While loops vs. for loops comparison

✦

KEY TAKEAWAY

Think of a for loop like boarding a roller coaster — you know exactly how many loops you'll take. A while loop is more like driving until you find a gas station. You don't know how far you'll go, but you know the condition that will make you stop.

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 NowWhat's Coming Next
While loop with a counter variableNested 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 iterationsAlgorithm efficiency — analyzing how loop count grows with input size (Big O notation).
Simple condition checkEvent 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

A common advanced pattern looks like this: 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

Explain in your own words why a while loop needs an update step inside the loop body. What happens if you forget to include one?
Show answer
A while loop checks its condition before every iteration. If nothing inside the loop changes a variable used in that condition, the condition will evaluate to the same value (True) every time. This means the loop body will execute endlessly — an infinite loop. The update step is what causes the condition to eventually become False, allowing the loop to terminate. Without it, you must force-quit the program.

Question 2: BASIC CALCULATION

Trace the following code by hand and determine what it prints: n = 10 while n > 0: print(n) n -= 3 List every value that is printed, in order.
Show answer
Iteration 1: n = 10 (10 > 0 is True), prints 10, then n becomes 7. Iteration 2: n = 7, prints 7, then n becomes 4. Iteration 3: n = 4, prints 4, then n becomes 1. Iteration 4: n = 1, prints 1, then n becomes −2. Now n = −2, and −2 > 0 is False, so the loop stops. The output is: 10, 7, 4, 1.

Question 3: INTERMEDIATE

Write a while loop that calculates the sum of all even numbers from 2 to 50 (inclusive). Store the result in a variable called even_sum and print it after the loop. How many iterations does your loop perform?
Show answer
One correct solution: 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

A password system gives the user at most 3 attempts to enter the correct password, which is "python123". Write a while loop that keeps asking for the password, tracks the number of attempts, and prints "Access granted" if correct or "Account locked" after 3 failed attempts. Use two conditions in your while statement.
Show answer
Here is one approach: 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

Consider the following code: 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
This loop will NOT terminate. Starting at x = 1 and adding 3 each time, x takes the values 1, 4, 7, 10 — wait, it does hit 10! Actually, let's trace carefully: x = 1, then 4, then 7, then 10. When x = 10, the condition x != 10 is False, so the loop does stop. However, the question highlights an important principle: if the step size were different (say x += 2 with values 1, 3, 5, 7, 9, 11...), x would skip right over 10 and loop forever. The safer fix is to change the condition from 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.

Varsity Tutors • Computer Programming 1 (Python) • While Loops