PYTHON FUNDAMENTALS: PROGRAMMING FOUNDATIONS / L04LOOPS AND ITERATION
课程 · 12 · 04 / 12
LESSON 04 · BEGINNER · 45 MIN · ◆ 2 INSTRUMENTS

Loops and Iteration

Master for and while loops to repeat operations efficiently. Learn about loop control with break and continue.

TIP

Learning Objectives: After this lesson, you'll master for and while loops to repeat operations efficiently, understand iteration patterns, and learn loop control with break and continue.

Understanding Loops: The Assembly Line Analogy

Before writing any code, let's understand what loops do through a powerful real-world analogy:

Loops are like assembly lines in a factory.

Imagine a car manufacturing plant:

  • Cars move down the assembly line → Items in your collection (list, range)
  • Each station performs the same task → Your loop body (the code that repeats)
  • Workers repeat the task for every car → Python executes the code for every item
  • The line stops when the last car is done → Loop ends when collection is exhausted

This is EXACTLY what Python loops do - they take a collection of items and perform the same operation on each one!

Visualizing Loops in Action

Let's see loops work before we write any code:

FIG. 02Algorithm Stepper
INTERACTIVE
LOADING INSTRUMENT
Fig. 02Step-through execution of algorithms and code
FIG. 04Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 04Interactive Python code execution environment

Why Do We Need Loops?

Imagine you need to print "Hello" 100 times. Without loops, you'd write:

print("Hello") print("Hello") print("Hello") # ... 97 more times!

Loops let you repeat code efficiently. They're essential for:

  • Processing collections of data (like the assembly line)
  • Repeating operations automatically
  • Automating repetitive tasks
  • Building interactive programs

For Loops: Iterating Over Collections

The for loop is perfect when you know what you want to iterate over:

FIG. 06Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 06Interactive Python code execution environment

The range() Function

range() is your best friend for creating number sequences:

FIG. 08Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 08Interactive Python code execution environment

While Loops: Repeating Until a Condition is Met

While loops continue as long as a condition is True:

FIG. 10Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 10Interactive Python code execution environment

Loop Control: break and continue

Control loop execution with break and continue:

FIG. 12Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 12Interactive Python code execution environment

Nested Loops

Loops inside loops for multi-dimensional processing:

FIG. 14Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 14Interactive Python code execution environment

Loop Execution Step-by-Step

Let's trace through a loop execution to see exactly what happens:

FIG. 16Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 16Interactive Python code execution environment

Common Loop Patterns

Pattern 1: Accumulation

FIG. 18Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 18Interactive Python code execution environment

Pattern 2: Building New Collections

FIG. 20Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 20Interactive Python code execution environment

Pattern 3: Finding Items

FIG. 22Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 22Interactive Python code execution environment

Practical Examples

Example 1: Grade Calculator

FIG. 24Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 24Interactive Python code execution environment

Example 2: Number Guessing Game

FIG. 26Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 26Interactive Python code execution environment

Practice Exercises

Exercise 1: Sum Calculator

FIG. 28Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 28Interactive Python code execution environment

Exercise 2: Pattern Generator

FIG. 30Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 30Interactive Python code execution environment

Exercise 3: List Processing

FIG. 32Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 32Interactive Python code execution environment

Key Takeaways

For loops iterate over collections (lists, strings, ranges)
While loops repeat while a condition is true
range() generates number sequences: range(start, stop, step)
break exits a loop early
continue skips to the next iteration
Nested loops handle multi-dimensional data
Common patterns - accumulation, filtering, searching, building collections

Connections: Loops Across Programming and Beyond

🔗 Connection to Mathematics

Loops are closely related to mathematical concepts:

  • Sigma notation (Σ): sum = Σ(i=1 to n) i is exactly what a loop does
  • Sequences and series: Loops process mathematical sequences
  • Iteration in algorithms: Many mathematical algorithms use iteration (Newton's method, etc.)

🔗 Connection to Other Languages

Loops exist in all programming languages with slight variations:

PythonJavaScriptJavaC++
for item in list:for (let item of list) {for (Type item : list) {for (auto item : list) {
while condition:while (condition) {while (condition) {while (condition) {
range(n)Array(n).keys()IntStream.range(0, n)Manual counter

🔗 Connection to Real-World Systems

  • Assembly lines: Manufacturing (our main analogy)
  • Data pipelines: Processing streams of data
  • Music loops: Repeating musical patterns
  • Video frames: Rendering each frame in sequence
  • Batch processing: Processing files, emails, transactions

🔗 Connection to Future Python Topics

  • List comprehensions: Loops written in one line (next lesson preview)
  • Functions: Loops often live inside functions for reusability
  • Recursion: An alternative to loops (advanced topic)
  • Iterators and generators: Advanced iteration patterns
  • Async loops: Handling concurrent operations

🔗 Connection to Algorithms

Loops are fundamental to classic algorithms:

  • Searching: Linear search, binary search
  • Sorting: Bubble sort, selection sort, insertion sort
  • Graph traversal: Visiting nodes (BFS, DFS)
  • Dynamic programming: Building solutions iteratively

Remember: Understanding loops deeply now will make all future programming concepts easier!

Next Steps

In the next lesson, we'll dive deep into functions - how to create reusable code blocks, understand parameters and return values, and explore scope concepts.


Ready to make your code more organized and reusable? The next lesson will teach you the power of functions!


Further Reading

Visualize It

  • Python Tutor — paste a for loop with enumerate or zip and watch each iteration's variable bindings. The mental model becomes obvious in 30 seconds.

Official Docs

Tutorials

Comprehensions (the Pythonic Way to Iterate)

Books

  • Book: Effective Python — Items 13–22 cover loop pitfalls (assignment expressions, comprehensions, generators, iterator protocol).
  • Book: Fluent Python — Chapter 17 ("Iterators, Generators, and Classic Coroutines"). Definitive treatment.