# Iterate over a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# Iterate over a string
for char in 'Python':
print(char)
# range() — most common with for
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 8): # 2, 3, 4, 5, 6, 7
print(i)
for i in range(0, 20, 3): # 0, 3, 6, 9, 12, 15, 18
print(i)
# Reverse range
for i in range(5, 0, -1): # 5, 4, 3, 2, 1
print(i)
# enumerate — get index + value
for i, fruit in enumerate(fruits):
print(f'{i}: {fruit}')
# zip — iterate parallel sequences
names = ['Alice', 'Bob']
ages = [25, 30]
for name, age in zip(names, ages):
print(f'{name} is {age}')# Basic while
count = 0
while count < 5:
print(count)
count += 1
# While with condition
password = ''
while password != 'secret':
password = input('Enter password: ')
print('Access granted!')
# Infinite loop with break
while True:
command = input('Command (q to quit): ')
if command == 'q':
break
print(f'Running: {command}')# Find first even number
nums = [1, 3, 5, 4, 6, 8]
for n in nums:
if n % 2 == 0:
print(f'First even: {n}')
break
# Output: First even: 4
# break only exits the INNERMOST loop
for i in range(3):
for j in range(3):
if j == 1:
break # Only breaks inner loop!
print(f'{i},{j}')
# Output: 0,0 1,0 2,0# Print only odd numbers
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i)
# Output: 1, 3, 5, 7, 9
# Skip invalid data
nums = [1, -1, 2, -2, 3, None, 4]
for n in nums:
if n is None or n < 0:
continue
print(n)
# Output: 1, 2, 3, 4# Empty block placeholder
for i in range(5):
pass # TODO: implement later
# In class/function stubs
class MyError(Exception):
pass # Will add custom logic later
def todo_function():
pass # Placeholder
# Minimal if/else structure
x = 10
if x > 5:
print('Big')
else:
pass # Explicitly do nothing# else runs ONLY if loop completes without break
for n in range(2, 10):
for i in range(2, n):
if n % i == 0:
break
else:
print(f'{n} is prime')
# Output: 2, 3, 5, 7 are prime
# Search pattern
names = ['Alice', 'Bob', 'Charlie']
for name in names:
if name == 'David':
print('Found David!')
break
else:
print('David not found!') # This runsCreate a function `find_prime_factors(n)` that returns a list of all prime factors of n (with repetition). Use a while loop to divide by each factor. Create another function `fizzbuzz(n)` that returns a list where: multiples of 3 → 'Fizz', multiples of 5 → 'Buzz', both → 'FizzBuzz', others → the number itself. Use for loop with continue/elif logic.