
Python
For loops are perfect when you know exactly how many times you need to repeat something.
for variable in sequence:
# code to repeat
print(variable)Three essential parts:
1. `for` — keyword
2. `variable` — takes each value from the sequence
3. `sequence` — the range or list to iterate over
The `range()` function generates a sequence of numbers. It's the most common way to loop a specific number of times.
# range(stop) - counts from 0 to stop-1
for i in range(5):
print(i) # Prints: 0, 1, 2, 3, 4
# range(start, stop) - counts from start to stop-1
for i in range(2, 5):
print(i) # Prints: 2, 3, 4
# range(start, stop, step) - counts with a step
for i in range(0, 10, 2):
print(i) # Prints: 0, 2, 4, 6, 8Example 1: Simple counting
# Count from 1 to 5
for number in range(1, 6):
print(f"Number: {number}")Example 2: Multiplication table
# Print the 5 times table
for i in range(1, 11):
result = 5 * i
print(f"5 × {i} = {result}")Example 3: Accumulating values
# Sum numbers from 1 to 100
total = 0
for number in range(1, 101):
total = total + number
print(f"Sum: {total}") # 5050For loops work perfectly with lists:
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(f"I like {fruit}")| Situation | Use | Example |
|---|---|---|
| Count 1 to 10 | `range(1, 11)` | `for i in range(1, 11):` |
| Loop 5 times | `range(5)` | `for i in range(5):` |
| Process list | List directly | `for item in my_list:` |
| Every 2nd number | `range(0, 10, 2)` | `for i in range(0, 10, 2):` |
| Concept | Remember |
|---|---|
| range(n) | Starts at 0, goes up to n-1 |
| Syntax | `for variable in sequence:` |
| Indentation | Code inside loop must be indented |
| Variable | Creates new variable each iteration |
Explore While Loops Basics for condition-based repetition!
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward