Skip to main content

Repetition with Loops

Imagine you need to print the numbers 1 through 100. You could write 100 separate print() statements—but that would be tedious, error-prone, and wasteful. Or imagine checking a password: you want to give the user three attempts to enter the correct password. You don't know how many tries they'll need, but you know the loop should stop after three failures.

This is where loops shine. Loops automate repetition, letting you run the same code multiple times without copying it. Python gives you two fundamental loop types: for loops for definite iteration (when you know how many times to repeat) and while loops for indefinite iteration (when repetition depends on a changing condition). In this lesson, you'll learn both, understand when to use each, and recognize how to avoid common pitfalls like infinite loops.

Why Automate Repetition?

In real-world programs, repetition is everywhere:

  • Processing data: Apply the same transformation to every item in a list
  • User input validation: Keep asking until the user provides valid input
  • Countdown timers: Count down from 10 to 1 for a game or app
  • Batch operations: Convert 100 files from one format to another

Without loops, you'd copy-paste code hundreds of times. With loops, you write the logic once and let Python handle the repetition. This makes your code shorter, clearer, and easier to maintain.

For Loops: Definite Iteration

A for loop repeats code a specific number of times. You use it when you know how many iterations you need—or when you're iterating over a sequence (like a list of items).

Basic For Loop with range()

The simplest for loop uses range() to generate a sequence of numbers:

Loading Python environment...

Expected Output:

1
2
3
4
5
6
7
8
9
10

How it works:

  1. range(1, 11) generates numbers from 1 up to (but not including) 11
  2. The loop variable i takes each value in sequence: 1, then 2, then 3, ... up to 10
  3. The indented print(i) runs once for each value of i
  4. When range() runs out of numbers, the loop ends

💬 AI Colearning Prompt

"Explain how for loops work under the hood with range() and iteration in Python."

Understanding range()

The range() function generates number sequences. It has three forms:

1. One argument (stop)

Loading Python environment...

Output:

0
1
2
3
4

Generates: 0, 1, 2, 3, 4 (5 numbers total, starting from 0)

2. Two arguments (start, stop)

Loading Python environment...

Output:

2
3
4
5

Generates: 2, 3, 4, 5 (starts at 2, stops before 6)

3. Three arguments (start, stop, step)

Loading Python environment...

Output:

2
4
6
8
10

Generates: 2, 4, 6, 8, 10 (starts at 2, stops before 11, increments by 2)

Key Insight: range(start, stop, step) NEVER includes the stop value. This is Python's convention: range(1, 11) gives you 1-10, not 1-11.

🎓 Expert Insight

In AI-native development, you don't memorize range() parameters—you understand WHEN you need a number sequence. Syntax is cheap; recognizing "I need to repeat N times" is gold.

Practical Example: Countdown Timer

Loading Python environment...

Expected Output:

T-minus 10 seconds
T-minus 9 seconds
T-minus 8 seconds
T-minus 7 seconds
T-minus 6 seconds
T-minus 5 seconds
T-minus 4 seconds
T-minus 3 seconds
T-minus 2 seconds
T-minus 1 seconds
Liftoff!

How it works:

  • range(10, 0, -1) counts DOWN from 10 to 1 (step = -1)
  • Loop runs 10 times (i = 10, 9, 8, ..., 1)
  • After the loop finishes, print("Liftoff!") runs once

While Loops: Indefinite Iteration

A while loop repeats code as long as a condition remains True. You use it when you don't know in advance how many iterations you'll need—the loop continues until some condition changes.

Basic While Loop Syntax

Loading Python environment...

Expected Output:

1
2
3
4
5

How it works:

  1. Before each iteration, Python checks: Is count <= 5?
  2. If True, the indented code runs
  3. count += 1 increases count by 1
  4. Loop repeats until count becomes 6 (then count <= 5 is False)
  5. Loop ends

CRITICAL: The loop variable (count) MUST change inside the loop. If it doesn't, the condition stays True forever, creating an infinite loop.

Practical Example: User Input Validation

Loading Python environment...

How it works:

  • Loop continues while age is outside valid range (less than 1 OR greater than 120)
  • User is prompted repeatedly until they enter a valid age (1-120)
  • Once a valid age is entered, condition becomes False and loop exits

Loop Termination Conditions: How to Avoid Infinite Loops

An infinite loop runs forever because its condition never becomes False. This is one of the most common beginner errors.

Example of Infinite Loop (DON'T DO THIS)

Loading Python environment...

What happens:

  • count starts at 1
  • Condition count <= 5 is True
  • Loop prints 1, then checks condition again
  • count is still 1, so condition is still True
  • Loop prints 1 again... and again... forever

How to avoid infinite loops:

  1. Always update the loop variable inside the loop body
  2. Ensure the condition can eventually become False
  3. Test with small values to verify loop exits correctly
  4. Use Ctrl+C to stop a runaway loop if you accidentally create one

Fixed Version

Loading Python environment...

For vs While: When to Use Each

Both loop types can accomplish many of the same tasks, but each has its ideal use cases:

Comparison diagram showing for loop vs while loop characteristics, use cases, and when to choose each loop type

Loop TypeUse WhenExample Scenarios
forYou know how many iterations you needPrint numbers 1-100, process each item in a list, run code exactly N times
whileRepetition depends on a changing conditionUser input validation, retry logic until success, game loop until player quits

Rule of Thumb:

  • Known count → for loop
  • Condition-based → while loop

🤝 Practice Exercise

Ask your AI: "Show me the same task (print numbers 1-5) implemented with BOTH a for loop and a while loop. Then explain when each approach is more appropriate."

Expected Outcome: You'll see both implementations side-by-side and understand the tradeoffs between definite and indefinite iteration.

AI Companion Section: Comparing For and While

Let's solve the same problem both ways to see the differences:

Task: Print numbers 1 through 5

Using for loop:

Loading Python environment...

Using while loop:

Loading Python environment...

Comparison:

AspectFor LoopWhile Loop
ClarityMore concise: one line manages iterationRequires explicit variable initialization and update
SafetyCan't accidentally create infinite loop with range()Risk of infinite loop if you forget to update variable
Use CaseWhen you know iteration countWhen iteration depends on condition

Which is better? For this task, for loop is clearer and safer. Use while when you truly need condition-based repetition (like user input validation).

Infinite Loop Demonstration + Fix

Infinite Loop (⚠️ Warning: Don't run this):

Loading Python environment...

Fixed Version:

Loading Python environment...

The fix: Added counter += 1 so the loop variable changes and the condition eventually becomes False.

Red Flags to Watch For

When working with loops, watch for these common errors:

🚩 Infinite Loops

Symptom: Program hangs, repeats output forever, or becomes unresponsive

Causes:

  • Forgot to update loop variable in while loop
  • Condition can never become False
  • Update logic is inside an unreachable if block

Fix: Ensure loop variable changes each iteration and condition can become False

AI Troubleshooting Prompt:

"I have a while loop that runs forever. Here's my code: [paste code]. What's wrong and how do I fix it?"

🚩 Off-by-One Errors

Symptom: Loop runs one too many or one too few times

Example:

Loading Python environment...

Fix: Remember range(start, stop) goes UP TO but DOES NOT INCLUDE stop

AI Troubleshooting Prompt:

"My for loop with range(1, 10) only prints up to 9 instead of 10. Why?"

🚩 Loop Variable Scope Confusion

Symptom: Trying to use loop variable outside loop or getting unexpected value

Example:

Loading Python environment...

What happens: Loop variable i persists after loop ends with its last value (4)

Best Practice: Don't rely on loop variable value after loop; use meaningful names (for item in items)

AI Troubleshooting Prompt:

"Why does my loop variable still exist after the loop ends? Is that expected?"

🚩 Step Zero Error

Symptom: ValueError: range() arg 3 must not be zero

Example:

Loading Python environment...

Fix: Step must be non-zero (positive to count up, negative to count down)

AI Troubleshooting Prompt:

"I got 'range() arg 3 must not be zero' error. What does this mean?"

Try With AI

Ready to master for and while loops for repetition?

🔍 Explore Loop Types:

"Compare for loops and while loops with examples. When should I use for (iterating over sequence) vs. while (condition-based)? Show me: for loop over range(10), for loop over list, while loop with counter, while loop with user input. Why does for loop prevent infinite loops?"

🎯 Practice Loop Patterns:

"Create a number guessing game: computer picks random 1-100, user guesses until correct. Use while loop for repeated guessing, comparison operators for feedback (too high/low), break when correct. Then convert it to for loop with maximum 10 attempts. Compare the two approaches."

🧪 Test Loop Edge Cases:

"Demonstrate these loop edge cases: (1) for loop over empty list—does it run? (2) while True with no break—what happens? (3) range(0)—does it iterate? (4) nested loops—how many iterations for range(3) inside range(4)? Show me the output for each."

🚀 Apply to Your Iteration Needs:

"I'm building [describe your application]. Help me choose between for and while loops for: processing list items, reading file lines, retrying failed operations, or game loops. For each case, explain why that loop type is the better choice and show example code."