Chapter 4: The for Loop — One by One, In Order¶
Definite vs Indefinite Loops¶
| while | for | |
|---|---|---|
| Type | Indefinite loop | Definite loop |
| When | While condition is True | Until end of sequence |
| Count | May not know before running | Fixed by sequence length |
for iterates through a sequence (list, string, range, etc.) from start to finish, one element at a time.
for Basic Structure¶
for variable in sequence:
code to execute
for i in [1, 2, 3, 4, 5]:
print(i)
1
2
3
4
5
i takes each value from the list one by one.
range() — Creating Number Sequences¶
range(stop) # 0 to stop-1
range(start, stop) # start to stop-1
range(start, stop, step) # start to stop-1, stepping by step
list(range(3)) # [0, 1, 2]
list(range(1, 5)) # [1, 2, 3, 4]
list(range(1, 10, 2)) # [1, 3, 5, 7, 9]
list(range(5, 0, -1)) # [5, 4, 3, 2, 1]
for i in range(5):
print(i, end=" ")
0 1 2 3 4
Lists¶
A list is an ordered collection of values.
animals = ["dog", "cat", "lion", "python", "fox", "wolf"]
print(animals[0]) # dog (first item, index starts at 0)
print(animals[2]) # lion
print(animals[-1]) # wolf (last item)
for animal in animals:
print("Hello,", animal)
Hello, dog
Hello, cat
Hello, lion
Hello, python
Hello, fox
Hello, wolf
Iterating Over Strings¶
Strings are sequences too. You can extract one character at a time.
for ch in "PYTHON":
print(ch * 2, end="")
PPYYTTHHOONN
_ — When You Don't Need the Value¶
Use _ when only the iteration count matters and the variable value is unused.
for _ in range(3):
print("Hello!")
Hello!
Hello!
Hello!
Nested for Loops¶
You can place a for loop inside another for loop.
for i in range(3): # outer: 3 times
for j in range(4): # inner: 4 times
print("*", end="")
print()
****
****
****
Each time the outer loop runs once, the inner loop runs from start to finish.
# Full multiplication table
for i in range(2, 10):
for j in range(1, 10):
print(f"{i} × {j} = {i*j}", end="\t")
print()
break and continue¶
They work the same way as in while loops.
# break: exit loop immediately when condition is met
for i in range(10):
if i == 5:
break
print(i, end=" ")
0 1 2 3 4
# continue: skip the rest of this iteration
for i in range(10):
if i % 2 == 0:
continue
print(i, end=" ")
1 3 5 7 9
len() — Getting the Length¶
A = [10, 20, 30, 40, 50]
print(len(A)) # 5
for i in range(len(A)):
print(i, A[i])
0 10
1 20
2 30
3 40
4 50
Use range(len(A)) when you need both the index and the value.
The in Operator — Check Membership¶
print(3 in [1, 2, 3, 4, 5]) # True
print(6 in [1, 2, 3, 4, 5]) # False
print("a" in "apple") # True
Combined with conditionals:
fruits = ["apple", "banana", "grape"]
target = input("Find fruit: ")
if target in fruits:
print(target, "is available!")
else:
print(target, "is not available.")
Introduction to Algorithms¶
Greedy Algorithm — Making Change¶
Use the largest denomination first, as many as possible.
amount = int(input("Change amount: "))
coins = [500, 100, 50, 10, 1]
result = []
for coin in coins:
count = amount // coin
amount = amount % coin
result.append((coin, count))
for coin, count in result:
if count > 0:
print(f"{coin}: {count} coins")
Change amount: 1234
500: 2 coins
100: 2 coins
50: 0 coins
10: 3 coins
1: 4 coins
Brute Force — Exhaustive Search¶
Try every possible combination.
# Find two-digit numbers whose digits sum to 10
for n in range(10, 100):
ones = n % 10
tens = n // 10
if ones + tens == 10:
print(n, end=" ")
19 28 37 46 55 64 73 82 91
Practice Missions¶
Mission 1: Star Pyramid (for version)¶
*
**
***
****
*****
n = 5
for i in range(n):
# Write your code here
pass
Mission 2: Find the Minimum¶
Without using min(), find the smallest value in a list using a for loop.
numbers = [34, 7, 23, 32, 5, 62]
# Write your code here
# Minimum: 5
Mission 3: FizzBuzz¶
Print numbers 1 to 30, but: - Multiples of 3 → "Fizz" - Multiples of 5 → "Buzz" - Multiples of 15 → "FizzBuzz"
for i in range(1, 31):
# Write your code here
pass
# 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz ...
Mission 4: Greedy — Minimum Coins¶
Calculate the minimum number of coins for a given amount.
amount = int(input("Amount: "))
coins = [500, 100, 50, 10, 1]
total_count = 0
# Write your code here
# Amount: 1730
# Minimum coins: 7 (500×3, 100×2, 10×3)
Mission 5: Brute Force — PIN Cracker¶
Print all 4-digit PINs (0000–9999) whose digits sum to a given value.
target = int(input("Digit sum: "))
# Use nested for loops or range(10000)
# Digit sum: 5
# 0005 0014 0023 ... 5000
Key Summary¶
| Concept | Description |
|---|---|
for variable in sequence: |
Iterate through sequence one element at a time |
range(n) |
Numbers from 0 to n-1 |
range(a, b, step) |
Numbers from a to b-1, stepping by step |
| List | [val1, val2, ...] — ordered collection, index starts at 0 |
| String iteration | Can extract one character at a time |
_ |
When the loop variable is not needed |
| Nested for | for inside for — 2D iteration |
len() |
Length of a sequence |
in |
Check if a value exists in a sequence → bool |
break |
Exit loop immediately |
continue |
Skip this iteration, move to next |
| Greedy algorithm | Make the best choice at each step |
| Brute force | Try all possible combinations |