Chapter 1 of ?
python 19 min read

Python for Data Science — Chapter 9: Loops

Module 3 — Control Flow

Chapter 9: Loops

Repeat computations efficiently in Python. Learn to generate number series using range(), repeat tasks with for and while loops, step across multi-dimensional spaces using nested loops, and control iteration flow with break, continue, and pass.

Why Do We Need Loops?

In programming, we often need to perform a task over and over again. Repeating the same code multiple times manually is inefficient, error-prone, and makes codebase maintenance difficult. Loops solve this by allowing us to execute a block of code repeatedly based on a sequence or a conditional check.

Before diving into loop constructs, let's explore Python's built-in helper for generating sequences: the range() function.

9.1 The range() Function

The range() function outputs an ordered sequence of numbers. It is lazy and does not explicitly generate list sequences in memory under Python 3 until iterated, which saves processing overhead.

  • range(n) : Generates values from 0 up to, but not including, n. E.g. range(3) yields 0, 1, 2.
  • range(start, end) : Generates values from start up to, but not including, end. E.g. range(10, 15) yields 10, 11, 12, 13, 14.
range() Parameter Explorer

Toggle parameter modes and slide parameters to inspect the generated values sequence.

Code RepresentationEvaluated Code Output
list(range(5)) ⇒ [0, 1, 2, 3, 4]

Try running this code block to verify how Python outputs range boundaries:

# Printing ranges
print("Single limit range(3):", list(range(3)))
print("Double limit range(10, 15):", list(range(10, 15)))

9.2 For Loops

A for loop repeats a set block of code a set number of times. You can iterate through lists using their index offsets, or you can loop directly across list elements without indexing variables.

For Loop Visual Square Replacer

Simulate replacing color squares with white squares. Select a loop method and click Step Iteration to watch the loop state update.

Active Code StatementVariable States & Console Out
Click Step to start the loop simulator...

Here is the index-based color mutation syntax alongside element loops and enumerate():

# List of color elements
squares = ["red", "yellow", "green", "purple", "blue"]

# Method 1: Index mutation loop
for i in range(5):
    squares[i] = "white"

# Method 2: Iterate elements directly
for square in squares:
    print(square)

# Method 3: Get both using enumerate()
for i, square in enumerate(squares):
    print("Index:", i, "Element:", square)

9.2.2 Nested Loops

A nested loop is a loop inside another loop. The inner loop runs to completion (covering all its iterations) for each single step or increment of the outer loop. This is highly useful for scanning grids, tables, and multi-dimensional matrices.

Nested Loops 2D Coordinate Grid Visualizer

Step through the grid loops. The outer loop index i handles grid rows, and the inner loop index j highlights columns within that row.

Nested Loops SyntaxIndex States & Output
Click Step to start the coordinate nested loops...

Here is the Python syntax used to print grid coordinates in row-by-row matrix form:

# Nested loops coordinate scan
for i in range(3):       # Outer Row loop
    for j in range(3):   # Inner Column loop
        print(f"Row {i}, Col {j}")

9.3 While Loops

A while loop executes a block of code repeatedly as long as a specified condition evaluates to True. Unlike for loops, you do not always know the exact number of iterations beforehand.

While Loop Orange Squares Copy Visualizer

Copy elements from squares list into new_squares list, but stop early when a non-orange square is encountered.

Source list: squares
Copied list: new_squares
Condition Check: squares[i] == 'orange'Index Check & Console Out
Click Step to start the while loop...

This is the Python while loop logic implementation used in the simulator above:

# Copy orange squares until non-orange square is met
squares = ["orange", "orange", "purple", "orange"]
new_squares = []
i = 0

while i < len(squares) and squares[i] == "orange":
    new_squares.append(squares[i])
    i += 1

print("Copied elements:", new_squares)

9.4 Loop Control Statements (break, continue, pass)

Loop control statements change the default sequential iteration path of a loop:

  • break : Terminate the entire loop immediately.
  • continue : Skip the rest of the current iteration block and skip directly to the next loop cycle.
  • pass : Do nothing. Used as a syntax placeholder when Python requires a statement block but no action is needed.
break, continue, and pass Simulator

Choose a statement rule to execute on item 3 as we iterate from 1 to 5. Observe how the instruction path and output values differ.

Code Control Flow PreviewVariable States & Printed Console Output
Click Step to start the control flow loop...

Try running this code block to verify how Python outputs loop control statements:

# Demonstrating control flow statements
print("Break demo (exits on 3):")
for val in [1, 2, 3, 4, 5]:
    if val == 3:
        break
    print("  Value:", val)

print("\nContinue demo (skips 3):")
for val in [1, 2, 3, 4, 5]:
    if val == 3:
        continue
    print("  Value:", val)

print("\nPass demo (placeholder):")
for val in [1, 2, 3, 4, 5]:
    if val == 3:
        pass  # does nothing
    print("  Value:", val)

Practice Quiz

Test your understanding of Python loops and control statements by answering the questions below.

Test Your Understanding

Done with this chapter?
Mark it complete to track your progress and unlock your certificate.
Next Up

Learner Reviews

Write a Review
Share your experience to help other learners.
Your Rating *