Level: Basic | Prerequisite: Week 4 (Conditional Statements)
Learning Goals
- Repeat a set number of times with
forandrange() - Repeat while the condition with
whileis true - Control the flow with
breakandcontinue - Understand nested loops
1. for Loop
Create a sequence of integers with range(start, end, step) and iterate.
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(1, 11): # 1 ~ 10
print(i, end=" ")
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)
You can also directly iterate over sequences like lists or strings (next week).
2. while Loop
Keep executing while the condition is True. The termination condition must change.
n = 1
while n <= 5:
print(n)
n += 1 #Without this, it's an infinite loop!
Decide termination based on user input:
while True:
cmd = input("Command (exit with quit):")
if cmd == "quit":
break
print(f"Execute: {cmd}")
3. break and continue
break— exit the loop immediatelycontinue— skip this iteration and continue to the next
for i in range(1, 11):
if i == 5:
continue #Skip 5
if i == 8:
break #End at 8
print(i, end=" ") # 1 2 3 4 6 7
4. Nested Loops
A loop inside a loop. Often used for multiplication tables and table printing.
for i in range(2, 10): #2-step~9-step
for j in range(1, 10): # ×1 ~ ×9
print(f"{i} × {j} = {i*j}")
print() #Space between steps
Key Examples (examples/)
| File | Content |
|---|---|
01_for_range.py |
for + range pattern |
02_while.py |
while loop |
03_break_continue.py |
break, continue |
04_nested.py |
nested loops (multiplication table) |
⚠️ Common Mistakes
- Infinite Loop
n = 1 while n <= 5: print(n) #n += 1 skipped → prints 1 infinitely
→ Force stop with Ctrl+C. Check if the termination condition changes.
-
Mistake thinking
range(1, 10)is 1~10range(1, 10)is 19 (10 not included). If you want 110, userange(1, 11). -
Missing Indentation
for i in range(5): print(i) # IndentationError -
Misunderstanding that
breakexits all loopsbreakonly exits the closest loop. For multiple breaks, use a flag variable. -
Changing the loop variable inside the loop
for i in range(5): i = 100 #In the next iteration, it goes back to 0, 1, 2...
❓ FAQ
Q1. When should we use for or while? A. Use for when the number of iterations is fixed, use while when it depends on a condition to end. Receiving user input is usually while.
Q2. I heard there is a for ... else statement?
A. If for completes normally (without break), else will execute. Not often used at the beginner stage.
Q3. Why start from 0?
A. It's a convention that computers count indexes from 0. When showing to people, you can start from 1 using enumerate(seq, start=1).
📝 Exercises (exercises/)
exercise1.md— Multiplication table (2~9 times)exercise2.md— Star printing (equilateral triangle + inverted triangle)exercise3.md— Number guessing game
Next Week
Week 6. Lists and Tuples — Handling multiple values at once