Python Loops - for, while, break
After completing this topic
You will be able to create loops with for and while, and control the flow with break and continue.
for loop - Repeating a fixed number of times
# Iterating through a listfruits = ["apple", "banana", "grape"]
for fruit in fruits: print(fruit)# apple# banana# grapefor variable in iterable: - Iterates through each element of a list, string, range, etc.
range() - Creating a sequence of numbers
# range(end) - From 0 to end-1for i in range(5): print(i)# 0, 1, 2, 3, 4
# range(start, end)for i in range(2, 6): print(i)# 2, 3, 4, 5
# range(start, end, step)for i in range(0, 10, 2): print(i)# 0, 2, 4, 6, 8range(5) creates the sequence 0 to 4 (exclusive of 5). In almost all programming languages, ranges are conventionally "end-exclusive".
while loop - Repeating while a condition is true
count = 0
while count < 5: print(f"count = {count}") count += 1
# count = 0# count = 1# count = 2# count = 3# count = 4for is suitable when you "know how many times to repeat," and while is suitable when you "don't know when it will end."
Beware of infinite loops
# β This will never stopcount = 0while count < 5: print(count) # If you forget `count += 1` β infinite loop!
# Intentional infinite loop (used in servers, games, etc.)while True: command = input("> ") if command == "quit": break print(f"Input: {command}")When using a while loop, always check "when will this loop end?"
break and continue
break - Exit the loop
# Exit immediately when 3 is foundfor i in range(10): if i == 3: print("Found it!") break print(i)# 0# 1# 2# Found it!break immediately exits the nearest loop.
continue - Skip the current iteration
# Skip even numbersfor i in range(6): if i % 2 == 0: continue print(i)# 1# 3# 5continue does not end the loop, but skips the current iteration and goes to the next iteration.
Nested loops
# Multiplication table for 2 and 3for dan in range(2, 4): print(f"--- {dan} times ---") for i in range(1, 10): print(f"{dan} x {i} = {dan * i}")You can put a loop inside another loop. The inner loop executes completely for each iteration of the outer loop.
enumerate - Get both index and value
names = ["Kim Hoon", "Lee Soo", "Park Jin"]
# When you need the indexfor i, name in enumerate(names): print(f"{i}: {name}")# 0: Kim Hoon# 1: Lee Soo# 2: Park Jinenumerate() creates a tuple of (index, value). It's cleaner than for i in range(len(names)).
Criteria for choosing between for and while
| Situation | Recommendation |
|---|---|
| Iterating through a list/range | for |
| Fixed number of iterations | for + range() |
| Condition-based repetition | while |
| Waiting for user input | while True + break |
In most cases, you will use for. Use while when the "ending condition is not data, but a state."