Python•Loops
Python For Loops and the range() Function
Unlike C-style counter loops, Python for loops are iterator-based. They step through items in an iterable directly, with range() generating numeric sequences.
Syntax
for item in iterable:
# execute code with item
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| item | Loop Variable | Takes the value of the current sequence element. |
| iterable | Iterable Object | List, range, string, dictionary, or generator. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Python locally:
# 1. Iterating with range(start, stop, step)
print("--- Squares Table ---")
for num in range(1, 5):
print(f"{num} squared = {num ** 2}")
# 2. Iterating with enumerate() for index & value
print("\n--- Tech Stack Ranking ---")
languages = ["Python", "JavaScript", "Rust"]
for index, lang in enumerate(languages, start=1):
print(f"#{index}: {lang}")Expected Output:
--- Squares Table --- 1 squared = 1 2 squared = 4 3 squared = 9 4 squared = 16 --- Tech Stack Ranking --- #1: Python #2: JavaScript #3: Rust
How It Works: Step-by-Step
- Lines 3-4: range(1, 5) produces numbers 1, 2, 3, 4 (stop 5 is exclusive).
- Lines 9-10: enumerate() pairs index with the corresponding element automatically.
Key Concepts
- range(start, stop, step) is zero-indexed by default and lazy-evaluated.
- enumerate(seq, start=1) produces tuples of (index, item) during iteration.
- Python for loops do not require manual index incrementing.
Common Mistake: Expecting range(1, 10) to include 10
The stop parameter in range() is exclusive. Use range(1, 11) to include 10.
❌ Incorrect
for i in range(1, 5): # Runs only up to 4
pass✅ Correct
for i in range(1, 6): # Runs from 1 through 5 inclusive
passRelated Python Tutorials & Compiler
Python While Loops: Syntax, Execution, and Conditions
A while loop repeatedly executes a target statement block as long as a given boolean condition remains True.
Python Break, Continue, and Pass Loop Control Statements
Control loop execution flow using break to exit early, continue to skip iterations, and pass as a placeholder.
Python Lists: Operations, Slicing, and Built-in Methods
Lists are ordered, mutable collections of items. They are one of the most versatile built-in data types in Python.
Python Online Compiler
Open in Compilra IDE
Run and test Python on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.