Module 2 ยท Lesson 7

Loops: for and while

๐Ÿ Pythonโฑ 15 min read๐Ÿ“– Core Concept

for Loops

Python's for loop iterates over any iterable โ€” lists, strings, ranges, dictionaries, files, and more. Unlike C-style for loops, Python's version is always "for each item in collection".

# Iterate over a list fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(f"I like {fruit}") # Iterate over a string (character by character) for char in "Python": print(char, end="-") # P-y-t-h-o-n- # Iterate over a range for i in range(5): # 0, 1, 2, 3, 4 print(i) for i in range(1, 6): # 1, 2, 3, 4, 5 print(i) for i in range(0, 10, 2): # 0, 2, 4, 6, 8 (step=2) print(i) for i in range(10, 0, -1): # 10, 9, 8, ... 1 (countdown) print(i)

enumerate() โ€” Index and Value Together

fruits = ["apple", "banana", "cherry"] # BAD โ€” old-school, don't do this for i in range(len(fruits)): print(i, fruits[i]) # GOOD โ€” Pythonic way for i, fruit in enumerate(fruits): print(f"{i}: {fruit}") # Start counting from 1 for i, fruit in enumerate(fruits, start=1): print(f"{i}. {fruit}") # 1. apple # 2. banana # 3. cherry

zip() โ€” Iterate Multiple Lists in Parallel

names = ["Alice", "Bob", "Carol"] scores = [95, 87, 92] grades = ["A", "B", "A"] for name, score, grade in zip(names, scores, grades): print(f"{name}: {score} ({grade})") # zip stops at the shortest iterable # Use itertools.zip_longest to continue to the longest

while Loops

Repeat a block while a condition is True. Always ensure the condition eventually becomes False.

count = 0 while count < 5: print(count) count += 1 # Must modify condition variable! # Classic input validation pattern while True: # Infinite loop until break user_input = input("Enter a positive number: ") if user_input.isdigit() and int(user_input) > 0: number = int(user_input) break print("Invalid! Please enter a positive integer.") print(f"You entered: {number}") # Countdown n = 10 while n > 0: print(n, end=" ") n -= 1 print("Go!")

Loop Control: break, continue, else

# break โ€” exit the loop immediately for i in range(10): if i == 5: break print(i) # Prints: 0 1 2 3 4 # continue โ€” skip to next iteration for i in range(10): if i % 2 == 0: continue # Skip even numbers print(i) # Prints: 1 3 5 7 9 # Loop else โ€” runs ONLY if loop completed without break # (Useful for search patterns) target = 7 for i in range(10): if i == target: print(f"Found {target}!") break else: print(f"{target} not found") # Practical: check if all items pass a condition items = [2, 4, 6, 8, 10] for item in items: if item % 2 != 0: print("Not all even!") break else: print("All items are even!") # Runs โ€” no break occurred

Useful Loop Patterns

# Accumulate results total = 0 for n in range(1, 101): total += n print(total) # 5050 # Build a list (better as comprehension, but useful to understand) squares = [] for x in range(1, 6): squares.append(x ** 2) # [1, 4, 9, 16, 25] # Iterate over dictionary person = {"name": "Alice", "age": 30, "city": "NYC"} for key, value in person.items(): print(f"{key}: {value}") # Nested loops โ€” multiplication table for i in range(1, 4): for j in range(1, 4): print(f"{i*j:3}", end="") print() # 1 2 3 # 2 4 6 # 3 6 9 # Flatten nested structure matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flat = [] for row in matrix: for num in row: flat.append(num) # Better as: flat = [n for row in matrix for n in row] # Fibonacci sequence a, b = 0, 1 for _ in range(10): # _ means "don't care about the variable" print(a, end=" ") a, b = b, a + b # 0 1 1 2 3 5 8 13 21 34

Key Takeaways

Practice Exercises

  1. Write a loop that prints the first 15 Fibonacci numbers.
  2. Find all prime numbers between 1 and 100 using a nested loop with break.
  3. Write a number guessing game: pick random.randint(1, 100), let the user guess with "too high"/"too low" hints, count and display attempts.
  4. Given two lists of equal length, use zip to create a dictionary pairing them, then print sorted by value descending.
โ† Conditionals