Control Flow - For Loops
Learn to repeat code easily with for loops
What You'll Learn
- What loops are
- Using for loops
- Looping through lists
- Using range()
What is a Loop?
A loop repeats code multiple times. Instead of writing same code again and again, write it once in a loop!
Without loop:
print("Hello")
print("Hello")
print("Hello")With loop:
for i in range(3):
print("Hello")Both do the same thing!
Basic for Loop
for i in range(5):
print(i)Output:
0
1
2
3
4
Note: Starts at 0, not 1!
Using range()
range() creates a sequence of numbers:
range(stop):
for i in range(3):
print(i)
# Shows: 0, 1, 2range(start, stop):
for i in range(1, 4):
print(i)
# Shows: 1, 2, 3range(start, stop, step):
for i in range(0, 10, 2):
print(i)
# Shows: 0, 2, 4, 6, 8Looping Through Lists
Visit each item in a list:
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)Output:
apple
banana
orange
Practice Examples
Example 1: Count to 10
for i in range(1, 11):
print(i)
# Shows: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10Example 2: Times table
number = 5
for i in range(1, 11):
result = number * i
print(f"{number} x {i} = {result}")Output:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...
Example 3: Sum numbers
total = 0
for i in range(1, 6):
total += i
print(f"Adding {i}, total is now {total}")
print(f"Final total: {total}")Example 4: Shopping list
items = ["milk", "eggs", "bread"]
print("Shopping List:")
for item in items:
print(f"- {item}")Looping Through Strings
Each letter is an item:
word = "Python"
for letter in word:
print(letter)Output:
P
y
t
h
o
n
Using Index with enumerate()
Get both position and value:
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")Output:
0: apple
1: banana
2: orange
Start from 1:
for index, fruit in enumerate(fruits, 1):
print(f"{index}: {fruit}")Output:
1: apple
2: banana
3: orange
Nested Loops
Loop inside a loop:
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i * j}")
print("---")break - Stop Loop Early
for i in range(10):
if i == 5:
break # Stop here
print(i)
# Shows: 0, 1, 2, 3, 4Example: Find number
numbers = [3, 7, 2, 9, 5]
for num in numbers:
if num == 9:
print("Found 9!")
breakcontinue - Skip to Next
for i in range(5):
if i == 2:
continue # Skip 2
print(i)
# Shows: 0, 1, 3, 4Example: Print odd numbers
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i)
# Shows: 1, 3, 5, 7, 9Real-World Examples
Example 1: Calculate average
scores = [85, 90, 78, 92, 88]
total = 0
for score in scores:
total += score
average = total / len(scores)
print(f"Average: {average}")Example 2: Find max number
numbers = [45, 23, 67, 12, 89, 34]
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
print(f"Maximum: {max_num}")Example 3: Create username list
names = ["John", "Sarah", "Mike"]
for name in names:
username = name.lower() + "123"
print(f"Username: {username}")Common Mistakes
Mistake 1: Forgetting colon
# Wrong
for i in range(5)
print(i)
# Correct
for i in range(5):
print(i)Mistake 2: Wrong indentation
# Wrong
for i in range(5):
print(i)
# Correct
for i in range(5):
print(i)Mistake 3: Modifying list while looping
# Risky
numbers = [1, 2, 3]
for num in numbers:
numbers.remove(num) # Don't do this!Quick Reference
Basic loop:
for i in range(5):
print(i)Loop through list:
for item in items:
print(item)With index:
for i, item in enumerate(items):
print(i, item)Stop early:
breakSkip one:
continueSummary
- for loops repeat code
- range() creates number sequences
- Loop through lists, strings, anything
- Use break to stop early
- Use continue to skip one
- Always use colon and indentation
What's Next?
Now let's learn about while loops for different kinds of repetition!