18 min read Repetition & Control Flow Lesson 8 of 16
Course 03 · Part 2 — Input, Operators & Control Flow

Loops: Repeating Tasks with Automated Power

Unlocking the Superhuman Strength of Tireless Iteration

In the previous lesson, we learned how programs make intelligent branching decisions using if/elif/else. But what if a task needs to run 5 times, 1,000 times, or 10,000,000 times? Would we copy and paste identical code millions of times? Of course not. The true superpower of a computer is its ability to perform billions of repetitive operations per second without boredom, fatigue, or error. The foundational programming structure enabling this automated repetition is the Loop.

Manual Copy-Paste vs. Intelligent Automation

Printing "Hello" 5 times by writing 5 print calls is tedious but manageable. But what if you must dispatch notification emails to 50,000 users, aggregate items in a 200-product order, or render 60 video game frames every second? Manual repetition collapses instantly. Loops instruct the computer: “Take this single block of instructions, and execute it repeatedly according to a specified sequence or condition.”

01 to 03 What is a Loop & The Two Primary Loop Types in Python

Stated formally:

A Loop is a fundamental control flow structure that repeats a statement or block of statements multiple times until a terminating condition is met or a sequence is exhausted.
Instruction ──> Repeat ──> Repeat ──> Terminating Condition ──> Done

In commercial software, loops power nearly every core subsystem: processing database query results, reading lines from files, streaming telemetry from IoT sensors, and driving the central game loop.

1. The `for` Loop (Definite Iteration)

Ideal when you want to iterate sequentially over a known sequence or collection—such as a range of numbers, characters in a string, or elements in a list.

2. The `while` Loop (Conditional Iteration)

Ideal when the exact number of iterations is unknown in advance, and the loop must continue executing as long as a specified boolean condition remains True.

04 to 07 Your First `for` Loop, the `range()` Function & Iteration

Let us observe Python's most concise and elegant for loop:

for i in range(5):
print("Hello")
# Output:
Hello
Hello
Hello
Hello
Hello

1. What Does `range(5)` Actually Produce?

range(5) generates an immutable numeric sequence that begins at 0 and stops immediately before 5. It generates: 0, 1, 2, 3, 4. Crucially, the upper boundary (5) is never included!

2. What is the Loop Variable (`i`)?

In the statement above, i is the target loop variable. At the beginning of each cycle, i automatically receives the next value from the sequence:

for i in range(5):
print(i)

In iteration 1, i = 0; in iteration 2, i = 1; continuing until i = 4.

3. What is an Iteration?

A single full execution of the code block contained within the loop body is formally called an iteration. Running range(3) executes exactly 3 full iterations.

08 to 10 The Mechanics of `range()`: Start, Stop, Step & Negative Reversal

The range() constructor supports up to three arguments to control its boundaries and progression:

1. Custom Start and Stop: range(start, stop)
for i in range(2, 6):
print(i)
# Output: 2, 3, 4, 5 (Stop value 6 is strictly excluded!)
2. Custom Step Interval: range(start, stop, step)
for i in range(0, 10, 2):
print(i)
# Output: 0, 2, 4, 6, 8 (Increments by 2 on each cycle)
3. Reverse Progression / Negative Step
for i in range(5, 0, -1):
print(i)
# Output: 5, 4, 3, 2, 1 (Rocket countdown sequence!)

11 to 13 Dynamic Expressions with Loop Variables & String Iteration

The loop variable is not merely an index to print; it acts as a dynamic parameter evaluated inside mathematical expressions:

Mathematical Multiplication:
for i in range(5):
print(i * 2)
# 0, 2, 4, 6, 8 (i is doubled on each cycle)
Countdown Program:
for i in range(3, 0, -1):
print(i)
print("Blast off!")

Remember: `for` Loops Iterate Over Any Iterable!

Beginners often mistakenly assume that for loops only operate on range(). In Python, a string is also a sequence of characters, meaning a for loop can walk through its characters directly:

word = "Python"
for char in word:
    print(char) # Sequentially prints: P, y, t, h, o, n

14 to 17 The `while` Loop: Architecture & Real-World Game Modeling

Python's second primary loop is the while loop. Its operating contract is simple: “Evaluate the condition—so long as it evaluates to True, continue running the indented block indefinitely.”

count = 1
while count <= 5:
print(count)
count += 1 # Incrementing count to avoid an infinite loop
`while` Loop Internal Evaluation Cycle:
1. count = 1 ──> (1 <= 5? True) ──> print(1) ──> count becomes 2
2. count = 2 ──> (2 <= 5? True) ──> print(2) ──> count becomes 3
...
5. count = 5 ──> (5 <= 5? True) ──> print(5) ──> count becomes 6
6. count = 6 ──> (6 <= 5? False!) ──> Loop terminates immediately!

Real-World Case: Video Game Player Lives

lives = 3
while lives > 0:
print(f"Playing... Remaining lives: {lives}")
lives -= 1 # Player sustains damage
print("Game Over! No lives left.")

18 Warning: The Infinite Loop Hazard & Safe Halts

If a while loop's test condition can never become False, the program enters an endless loop, consuming CPU cycles and freezing the shell:

# Critical Bug: Forgetting to mutate the counter!
count = 1
while count <= 5:
print(count) # count stays 1 forever, looping perpetually!

Should you trigger an unintended infinite loop in your terminal, press Ctrl + C immediately to send a keyboard interrupt signal and halt execution. Note that in long-running servers and message listeners, intentional while True: loops are commonplace.

19 to 21 Loop Control Statements: `break` vs. `continue`

Python provides two fine-grained keywords to alter the default progression of a loop mid-flight:

`break` — Immediate Early Exit

Completely terminates the entire loop structure immediately.

for i in range(10):
if i == 5: break
print(i)
# Output: 0, 1, 2, 3, 4 (Exits immediately when i hits 5)
`continue` — Skip Current Iteration

Skips the remainder of the current pass and advances directly to the next cycle.

for i in range(5):
if i == 2: continue
print(i)
# Output: 0, 1, 3, 4 (Pass 2 was skipped cleanly)

22 to 24 Harmonizing Loops with Conditions: Parity, Accumulators & Tables

When conditional branching (if) and accumulating variables are embedded inside a loop, our programs reach true algorithmic capabilities:

1. Filtering with Conditions: Even Numbers from 1 to 10
for i in range(1, 11):
if i % 2 == 0:
print(f"{i} is Even")
2. The Accumulator Pattern: Computing Sum of 1 to 5
total = 0
for i in range(1, 6):
total = total + i # Idiomatic shorthand: total += i
print(f"Total sum: {total}") # Output: 15
3. Automated Multiplication Table Generator
number = 5
for i in range(1, 11):
print(f"{number} × {i} = {number * i}")

25 & 26 Nested Loops: Dimensional Grids & Algorithmic Complexity

Nesting one loop inside another creates a Nested Loop. This construct is fundamental for navigating 2D Cartesian grids, matrix math, coordinate planes, and pixel surfaces:

for row in range(3):
for col in range(3):
print(f"Row {row}, Col {col}")

Multiplicative Execution & A Preview of Time Complexity

For each single iteration of the outer loop, the inner loop executes its entire range to completion! A 3-iteration outer loop hosting a 3-iteration inner loop yields 3 × 3 = 9 total operations. If both loops scale to 1,000 iterations, the body fires 1,000,000 times! This exponential scaling forms the bedrock of Big-O Notation and Time Complexity explored in our upcoming Data Structures & Algorithms course.

27 to 30 Data Processing, Iterables & Interactive Guessing Games

Real-world applications utilize loops to parse input streams and process dynamic collections effortlessly:

guessing_game.py
secret_number = 7
while True:
guess = int(input("Guess the secret number (1-10): "))
if guess == secret_number:
print("Jackpot! You guessed it correctly.")
break # Terminates the loop upon a correct answer
else:
print("Wrong guess. Try again!")

31 to 33 Computational Speed & The Gateway to Functions

Modern CPUs crunch through loop iterations with staggering velocity:

for i in range(1_000_000):
pass # Python completes one million passes in a fraction of a second!

Our foundational toolkit has expanded dramatically. We can take user input, maintain state in typed variables, evaluate logic, and execute tireless repetitions.

Variables → Data Types → Input/Output → Operators → Conditions → Loops

However, as programs scale in complexity, duplicating identical blocks of logic across files makes maintenance impossible. We require a mechanism that allows us to write a procedure once under a descriptive name, and call it whenever needed. This introduces our next major paradigm shift: Functions!

34 8 Hands-on Practice Challenges

Open loops_practice.py in your editor and conquer the following 8 programming exercises:

Challenge 1: Print 1 to 10 Use a for loop and range() to print integers 1 through 10 sequentially.
Challenge 2: All Even Numbers (1-100) Print all even numbers from 1 to 100 using either modulo check (i % 2 == 0) or step parameter (range(2, 101, 2)).
Challenge 3: Cumulative Sum (1-100) Initialize an accumulator total = 0 and sum all numbers from 1 to 100 (Expected output: 5050).
Challenge 4: Multiplication Table Generator Prompt the user for an integer and format its complete multiplication table from 1 through 10.
Challenge 5: Rocket Launch Countdown Execute a reverse countdown from 10 down to 1, followed by a final "Lift off!" message.
Challenge 6: Filter Positive Numbers Loop 5 times to prompt for numbers, filtering and printing only positive entries.
Challenge 7: Secret Number Guessing Game Construct an interactive while True loop prompting for guesses until the secret number matches, then break.
Challenge 8: Nested Star Triangle Pattern Use nested loops to construct a 5-tier right triangle pattern of stars (*, **, ***, ...).

35 🧠 Key Takeaways & Summary

Loops: The fundamental engine of repetitive automation in programming.
The `for` Loop: Ideal for definite iteration over sequences, strings, and collections.
The `while` Loop: Keeps running conditionally as long as a test expression remains true.
`break` vs. `continue`: `break` halts and exits the entire loop; `continue` skips only the current iteration cycle.
Accumulator Pattern: A persistent variable updated incrementally across iterations to aggregate final results.

Next Lesson: Functions — Modular Reusable Code

How do we write logic once and execute it anywhere effortlessly? Master function parameters, return values, and modular clean code.