Loops: For and While
Loops: For and While
Loops let you repeat code multiple times without writing it over and over.
For Loops
Use for when you know how many times to loop:
# Print numbers 0 to 4
for i in range(5):
print(i)
Output:
0
1
2
3
4
Looping Over Lists
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
Range Variations
# Start at 1, go to 5
for i in range(1, 6):
print(i) # 1, 2, 3, 4, 5
# Start at 0, go to 10, step by 2
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
# Count backwards
for i in range(5, 0, -1):
print(i) # 5, 4, 3, 2, 1
While Loops
Use while when you don't know how many iterations you need:
count = 0
while count < 5:
print(count)
count += 1 # Don't forget this!
Common Pattern: User Input
password = ""
while password != "secret":
password = input("Enter password: ")
print("Access granted!")
Break and Continue
Break - Exit the loop early
for i in range(10):
if i == 5:
break # Stop the loop
print(i)
# Prints: 0, 1, 2, 3, 4
Continue - Skip to next iteration
for i in range(5):
if i == 2:
continue # Skip this iteration
print(i)
# Prints: 0, 1, 3, 4
Nested Loops
Loops inside loops:
for i in range(3):
for j in range(3):
print(f"({i}, {j})")
Example: Multiplication Table
for i in range(1, 6):
for j in range(1, 6):
print(f"{i * j:3}", end=" ")
print() # New line after each row
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Loop with Else
Python has an unusual feature - loops can have an else clause:
for i in range(5):
if i == 10:
break
else:
print("Loop completed without break")
The else block runs only if the loop completes normally (no break).
Common Patterns
Sum of numbers
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print(f"Sum: {total}") # 15
Find an item
names = ["Alice", "Bob", "Charlie"]
search = "Bob"
for name in names:
if name == search:
print(f"Found {search}!")
break
else:
print(f"{search} not found")
Warning: Be careful with
whileloops - make sure your condition will eventually becomeFalse, or you'll create an infinite loop!