Chapter 6: Loops: Repeating Code 🔁

Imagine you need to print the numbers 1 through 100. You could write 100 separate print() statements, but that would be tedious and wasteful. What if you could tell Python: “Do this task 100 times”? That’s exactly what loops do!

Loops are one of the most powerful concepts in programming. They let you repeat code efficiently without copying and pasting. By the end of this chapter, you’ll be able to automate repetitive tasks and write programs that are both shorter and more powerful.


The while Loop 🔄

The while loop repeats a block of code as long as a condition remains True. Think of it as an if statement that keeps happening over and over until the condition becomes False.

Basic Syntax

while condition:
    # Code here runs repeatedly while condition is True
    print("Still going!")

The structure follows these rules:

  1. Start with the keyword while
  2. Write a condition (just like with if statements)
  3. End the line with a colon :
  4. Indent the code that should repeat

A Simple Example

count = 1

while count <= 5:
    print(f"Count: {count}")
    count += 1

print("Done counting!")

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Done counting!

Here’s what happens step by step:

  1. Python checks if count <= 5 (it is: 1 <= 5)
  2. The indented code runs, printing “Count: 1”
  3. count increases to 2
  4. Python checks the condition again (2 <= 5)
  5. The process repeats until count reaches 6
  6. When count is 6, the condition becomes False (6 <= 5 is false)
  7. The loop stops, and Python continues to the next line

The Importance of Updating

Notice how we update count inside the loop with count += 1. This is crucial! Without it, count would stay at 1 forever, and the loop would never end. This is called an infinite loop, and it’s a common mistake:

# WARNING: This creates an infinite loop!
count = 1
while count <= 5:
    print(f"Count: {count}")
    # Forgot to update count - it stays 1 forever!

If you accidentally create an infinite loop, you’ll need to stop your program manually (usually with Ctrl+C in the terminal).

Practical Examples

# Countdown timer
time_left = 10

while time_left > 0:
    print(f"{time_left} seconds remaining...")
    time_left -= 1

print("Time's up!")
# Keep doubling until we reach 100
number = 1

while number < 100:
    print(number)
    number *= 2

print(f"Final value: {number}")
# Password validator
password = ""

while password != "secret123":
    password = input("Enter the password: ")
    
    if password != "secret123":
        print("Wrong password! Try again.")

print("Access granted!")

Common while Loop Patterns 📋

Certain patterns appear frequently when using while loops. Understanding these patterns will speed up your coding.

Pattern 1: Counter Loops

Use a counter variable to control how many times the loop runs:

# Print "Hello" 3 times
counter = 0

while counter < 3:
    print("Hello!")
    counter += 1

This pattern is so common that Python created the for loop specifically for it (we’ll learn that soon).

Pattern 2: Accumulator Loops

Build up a result over multiple iterations:

# Sum the numbers 1 through 10
total = 0
number = 1

while number <= 10:
    total += number
    number += 1

print(f"The sum is: {total}")  # Shows: The sum is: 55

Pattern 3: Input Validation Loops

Keep asking until you get valid input:

age = -1  # Start with an invalid value

while age < 0 or age > 120:
    age = int(input("Enter your age (0-120): "))
    
    if age < 0 or age > 120:
        print("Invalid age. Please try again.")

print(f"You are {age} years old.")

Pattern 4: Sentinel-Controlled Loops

Continue until a special “stop” value is entered:

print("Enter numbers to add (type 0 to stop):")

total = 0
number = int(input("Enter a number: "))

while number != 0:
    total += number
    number = int(input("Enter a number: "))

print(f"The total is: {total}")

The value 0 acts as a sentinel — a signal to stop the loop.

Pattern 5: Flag-Controlled Loops

Use a boolean variable to control the loop:

playing = True

while playing:
    choice = input("Do you want to keep playing? (yes/no): ").lower()
    
    if choice == "no":
        playing = False
        print("Thanks for playing!")
    else:
        print("Let's keep going!")

The playing variable is a flag that determines whether the loop continues.


The for Loop with range() 🎯

While while loops are powerful, they can be verbose when you simply want to repeat something a specific number of times. The for loop with range() makes this much simpler.

Basic Syntax

for variable in range(number):
    # Code here runs 'number' times
    print("Repeated!")

Simple Counting

# Print numbers 0 through 4
for i in range(5):
    print(i)

Output:

0
1
2
3
4

Notice that range(5) produces 5 numbers, but they start at 0 and end at 4. This is because Python uses zero-based indexing — counting starts from 0.

How range() Works

The range() function generates a sequence of numbers. You can use it in three ways:

1. range(stop) — Start at 0, go up to (but not including) stop:

for num in range(5):
    print(num)
# Output: 0, 1, 2, 3, 4

2. range(start, stop) — Start at start, go up to (but not including) stop:

for num in range(1, 6):
    print(num)
# Output: 1, 2, 3, 4, 5

3. range(start, stop, step) — Start at start, increment by step:

# Count by twos
for num in range(0, 11, 2):
    print(num)
# Output: 0, 2, 4, 6, 8, 10
# Count backwards
for num in range(10, 0, -1):
    print(num)
# Output: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

Practical Examples

# Multiplication table for 7
for i in range(1, 11):
    result = 7 * i
    print(f"7 × {i} = {result}")
# Draw a pattern
for i in range(1, 6):
    print("*" * i)
# Output:
# *
# **
# ***
# ****
# *****
# Calculate sum with for loop
total = 0
for num in range(1, 101):
    total += num

print(f"Sum of 1 to 100: {total}")  # Shows: Sum of 1 to 100: 5050

When to Use for vs while

  • Use for when you know how many times to loop (or have a collection to iterate over)
  • Use while when you need to loop until a condition changes (unknown number of iterations)
# Use for: We know we want exactly 10 iterations
for i in range(10):
    print(f"Iteration {i}")

# Use while: We don't know how many guesses it will take
secret = 42
guess = int(input("Guess the number: "))

while guess != secret:
    print("Wrong! Try again.")
    guess = int(input("Guess the number: "))

Loop Control: break 🛑

Sometimes you need to exit a loop early, before the condition becomes False. The break statement lets you do exactly that — it immediately stops the loop and continues with the code after it.

Basic Usage

for i in range(10):
    if i == 5:
        break  # Exit the loop when i equals 5
    print(i)

print("Loop finished!")

Output:

0
1
2
3
4
Loop finished!

The loop stops as soon as i reaches 5, even though it was supposed to continue to 9.

Practical Examples

Example 1: Search and stop

# Find the first number divisible by 7
for num in range(1, 100):
    if num % 7 == 0:
        print(f"Found it: {num}")
        break  # No need to keep searching

Example 2: Exit on user command

print("Type 'quit' to exit")

while True:  # This would run forever...
    message = input("Enter a message: ")
    
    if message.lower() == "quit":
        break  # ...but break lets us exit
    
    print(f"You said: {message}")

print("Goodbye!")

Example 3: Limit attempts

attempts = 0
max_attempts = 3

while True:
    password = input("Enter password: ")
    attempts += 1
    
    if password == "secret123":
        print("Access granted!")
        break
    
    if attempts >= max_attempts:
        print("Too many failed attempts!")
        break
    
    print(f"Wrong password. {max_attempts - attempts} attempts left.")

Using break with while

The break statement is particularly useful with while True loops, which would otherwise run forever:

while True:
    choice = input("Continue? (yes/no): ").lower()
    
    if choice == "no":
        break
    
    print("Still running...")

print("Loop ended!")

Loop Control: continue ⏭️

While break exits the loop entirely, continue skips the rest of the current iteration and jumps to the next one. It’s like saying “skip this one, but keep going with the loop.”

Basic Usage

for i in range(10):
    if i % 2 == 0:
        continue  # Skip even numbers
    print(i)

Output:

1
3
5
7
9

When i is even, continue skips the print() statement and jumps to the next iteration.

Understanding the Difference

  • break — Exit the loop completely
  • continue — Skip to the next iteration
# Using break
for i in range(5):
    if i == 3:
        break
    print(i)
# Output: 0, 1, 2

# Using continue
for i in range(5):
    if i == 3:
        continue
    print(i)
# Output: 0, 1, 2, 4 (skips 3, but continues)

Practical Examples

Example 1: Filter out unwanted values

# Sum only positive numbers
total = 0

for num in range(-5, 6):
    if num <= 0:
        continue  # Skip non-positive numbers
    total += num

print(f"Sum of positive numbers: {total}")

Example 2: Skip invalid input

print("Enter 5 numbers (skip any errors):")

count = 0
total = 0

while count < 5:
    user_input = input(f"Number {count + 1}: ")
    
    if not user_input.isdigit():
        print("Invalid input, skipped!")
        continue  # Don't count this, ask again
    
    total += int(user_input)
    count += 1

print(f"Average: {total / 5}")

Example 3: Clean data processing

# Process only valid scores
scores = [85, -5, 92, 105, 78, 88, -10, 95]

valid_scores = 0
total = 0

for score in scores:
    if score < 0 or score > 100:
        continue  # Skip invalid scores
    
    valid_scores += 1
    total += score

if valid_scores > 0:
    average = total / valid_scores
    print(f"Average of valid scores: {average:.1f}")

Quick Recap 🎯

Excellent work! You’ve mastered the fundamentals of loops:

  • while loops repeat code as long as a condition is True
  • Counter, accumulator, and sentinel patterns are common loop structures
  • for loops with range() simplify counting and iteration
  • range(start, stop, step) gives you fine control over iteration
  • break exits a loop immediately
  • continue skips to the next iteration

Loops transform repetitive tasks into elegant, efficient code!


Hands-On Mini Project: Guess the Number 🎮

Let’s build a classic guessing game that uses everything you’ve learned: loops, conditionals, input, and loop control.

Your Mission

Create a number guessing game where:

  1. The computer “thinks” of a number between 1 and 100
  2. The player tries to guess it
  3. After each guess, give a hint (“too high” or “too low”)
  4. Count how many guesses it takes
  5. Let the player play again if they want

Example Solution

import random

print("=" * 50)
print("         GUESS THE NUMBER GAME")
print("=" * 50)
print()

playing = True

while playing:
    # Computer picks a random number
    secret_number = random.randint(1, 100)
    guesses = 0
    max_guesses = 10
    
    print("I'm thinking of a number between 1 and 100.")
    print(f"You have {max_guesses} guesses.\n")
    
    won = False
    
    # Guessing loop
    while guesses < max_guesses:
        # Get player's guess
        guess = int(input(f"Guess #{guesses + 1}: "))
        guesses += 1
        
        # Check the guess
        if guess == secret_number:
            print(f"\n🎉 Congratulations! You got it in {guesses} guesses!")
            won = True
            break
        elif guess < secret_number:
            print("📈 Too low! Try a higher number.")
        else:
            print("📉 Too high! Try a lower number.")
        
        # Show remaining guesses
        remaining = max_guesses - guesses
        if remaining > 0:
            print(f"   ({remaining} guesses left)\n")
    
    # If player didn't win
    if not won:
        print(f"\n😔 Out of guesses! The number was {secret_number}.")
    
    # Ask to play again
    print("\n" + "=" * 50)
    play_again = input("Play again? (yes/no): ").lower()
    
    if play_again != "yes":
        playing = False
        print("\nThanks for playing! Goodbye!")
    else:
        print("\n" + "=" * 50)
        print()

print()
print("=" * 50)

Challenge Yourself

Try enhancing the game with these features:

  1. Difficulty levels — Easy (1-50), Medium (1-100), Hard (1-500)
  2. Score tracking — Keep track of best score (fewest guesses)
  3. Hint system — Give hints like “divisible by 5” or “odd number”
  4. Range narrowing — Show the current possible range after each guess
  5. Time limit — Add a timer for each guess

Tips for Building

  • Test your game thoroughly with different inputs
  • Make sure the loop eventually ends (avoid infinite loops)
  • Give clear, helpful feedback after each guess
  • Use break when the player wins
  • Use a flag variable (playing) to control the main game loop

What’s Next?

In the next chapter, you’ll learn about lists — a way to store multiple values in a single variable. You’ll discover how to organize data, and you’ll combine lists with loops to process collections of information efficiently!

Get ready to level up your data handling skills!


Fantastic work! Loops are a cornerstone of programming, and you’ve mastered them!