Looping Statements in Python

Module 2 • Session 10 • Allocation: 1 Contact Hr

while loop for loop range() enumerate() for-else

Looping statements allow programs to execute a block of code repeatedly based on a condition or sequence. Python offers two core loop structures: while (condition-controlled) and for (collection or sequence-controlled).

1. The `while` Loop (Condition-Controlled)

A while loop continuously executes its code block as long as a test condition remains True. Ensure the loop state mutates during iteration to avoid infinite loops.

counter = 1 while counter <= 5: print(f"Iteration count: {counter}") counter += 1 # Increment state to guarantee loop termination print("Loop execution completed.")

2. The `for` Loop & Sequence Iteration

Unlike traditional count-based loops in C/Java, Python's for loop functions as an iterator driver over iterable objects like lists, strings, dictionaries, or generators.

frameworks = ["Django", "Flask", "FastAPI"] # Direct element iteration for framework in frameworks: print(f"Framework: {framework}") # String character iteration for char in "PYTHON": print(char, end="-") # Output: P-Y-T-H-O-N-

3. The `range()` Function

The range() function produces an immutable sequence of numbers on demand using three parameters: range(start, stop[, step]). Note that the stop boundary is exclusive.

Syntax Form Generated Output Sequence Description
range(5) 0, 1, 2, 3, 4 Defaults to start at 0 with step 1. Exclusive of 5.
range(2, 7) 2, 3, 4, 5, 6 Starts explicitly at 2 up to exclusive stop 7.
range(10, 0, -2) 10, 8, 6, 4, 2 Decrements backward from 10 to 1 with step -2.

4. Iteration Helpers: `enumerate()` & `zip()`

Python provides built-in iteration functions to track index positions and iterate over multiple collections in parallel without manual index handling.

tasks = ["Database Setup", "API Design", "Unit Testing"] assignees = ["Alice", "Bob", "Charlie"] # Track item index with enumerate() for index, task in enumerate(tasks, start=1): print(f"Task #{index}: {task}") # Parallel iteration with zip() for task, person in zip(tasks, assignees): print(f"'{task}' assigned to {person}")

5. Python's Unique `loop-else` Construct

Both for and while loops support an optional else clause. The else block executes only if the loop completes naturally without encountering a break statement.

Search & Validate Pattern: Use for-else when searching through collections. If an item is found, break skips the else block. If the loop completes without finding the target, the else block executes as a fallback.
numbers = [13, 27, 35, 41] target = 20 for num in numbers: if num == target: print(f"Found target {target}!") break else: print(f"Target {target} was not found in dataset.") # Executes because break was not hit
Infinite Loop Hazards: In while loops, double-check that sentinel variables are updated within all conditional paths. If a loop relies on external user input, always set a maximum iteration ceiling.

šŸ‹ļø Try It Yourself: Practice Challenges

Challenge 1: Prime Number Checker

Write a script using a for-else loop that checks whether an input integer is prime by testing factors up to its square root.

Challenge 2: Fibonacci Sequence Generator

Generate the first N terms of the Fibonacci sequence using a while loop with dual assignment state updates (a, b = b, a + b).

Challenge 3: Multi-List Aggregator with zip()

Given three lists representing product names, prices, and quantities sold, use a single for loop with zip() to compute and print individual line totals and a grand revenue total.

⚔ Interactive Sandbox (Loop Execution Engine)
Console Output:
Click "Run Code" above to execute interactive loop scripts...

šŸ“ Knowledge Check Quiz

1. What is generated by the call `list(range(5, 1, -1))`?
2. When does the `else` block connected to a `for` loop execute?
3. Which built-in function pairs elements from two iterables into tuples for parallel iteration?
Advertisement
Horizontal Ad Banner Slot (728x90 / Responsive)