- Core Definitions
- Key Differences:
forvswhile - The
forLoop - The
whileLoop - Loop Control Statements
- Quick Reference
- Pro Tips
- Common Mistakes to Avoid
- Iteration: The process of repeating a set of instructions. Each time the instructions are executed is called one "iteration".
forLoop: A loop that iterates over a sequence (like a list, dictionary, tuple, or string) or other iterable objects. It runs once for each item in the sequence.whileLoop: A loop that continues to execute as long as a certain condition remainsTrue.break: A keyword that immediately terminates the current loop, and the program continues at the next statement after the loop.continue: A keyword that skips the rest of the code inside the current iteration of the loop and proceeds to the next iteration.
| Feature | for Loop |
while Loop |
|---|---|---|
| Best For | Iterating over a known sequence | Looping as long as a condition is true |
| Typical Use | "For each item in this list..." | "Keep doing this until..." |
| Structure | for item in sequence: |
while condition: |
| Infinite Loop Risk | Low (stops when sequence ends) | High (if condition never becomes false) |
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like to eat {fruit}s.")# Loop 5 times (0 to 4)
for i in range(5):
print(f"Loop number {i}")
# Loop from 2 up to (but not including) 6
for i in range(2, 6):
print(f"Number: {i}")# Drawing a 5x5 square
size = 5
for i in range(size):
# For the first or last row, print a full line
if i == 0 or i == size - 1:
print("*" * size)
# For middle rows, print a star, spaces, and a star
else:
print("*" + " " * (size - 2) + "*")player_stats = {"name": "Alex", "level": 5}
# Using .items() to get key and value directly
for key, value in player_stats.items():
print(f"{key}: {value}")# Prints numbers 1 through 5
count = 1
while count <= 5:
print(count)
count = count + 1 # Crucial! This prevents an infinite loop.# Drawing a growing triangle
lines = 1
while lines <= 7:
print("*" * lines)
lines += 1 # Shortcut for lines = lines + 1command = ""
while command.lower() != "exit":
command = input("Enter command (or 'exit'): ")
print(f"Executing: {command}")Use break to exit a loop immediately, regardless of the loop's condition.
# Find the first person named "Bob" and then stop.
names = ["Alice", "Charlie", "Bob", "David"]
for name in names:
print(f"Checking {name}...")
if name == "Bob":
print("Found Bob!")
break # Exit the loop nowUse continue to skip the current iteration and move to the next one.
# Print all numbers from 0 to 9, but skip 5.
for i in range(10):
if i == 5:
continue # Skip the rest of this iteration
print(i)# Over a list
for item in my_list:
# do something with item
# For a specific number of times
for i in range(10):
# do something 10 times
# With index and item
for index, item in enumerate(my_list):
print(f"Index {index}: {item}")# Counter-based
i = 0
while i < 10:
# do something
i += 1 # Shortcut for i = i + 1
# User-input based (infinite loop with a break condition)
while True:
response = input("Continue? (y/n): ")
if response.lower() == 'n':
break # Exit condition-
forloops are forfor each: If you can phrase your problem as "for each item in my collection...", aforloop is almost always the right choice. It's safer and often more readable. -
whileloops are foruntil: If you can phrase your problem as "keep doing this until some condition changes...", awhileloop is what you need. Perfect for games, menus, and waiting for events. -
Combine Loops and
if: The real power comes when you putifstatements inside your loops to make decisions on each iteration. -
Use
enumerate()for Indexes: When you need both the index and the item from a list,enumerate()is cleaner than managing your own counter.
❌ Creating an Infinite while Loop
# Wrong: The condition `i < 5` never becomes false!
i = 0
while i < 5:
print("This will never stop!")
# You forgot to increment i!✅ Always Update the Condition Variable
# Correct
i = 0
while i < 5:
print(i)
i += 1 # The variable is updated, so the loop will end.❌ Forgetting to Convert input() to a Number
# Wrong: 'guess' will be a string, so guess != 7 will always be true!
secret_number = 7
guess = ""
while guess != secret_number:
guess = input("Guess the number: ") # guess is "7", not 7✅ Convert Input for Comparison
# Correct
secret_number = 7
guess = 0
while guess != secret_number:
guess = int(input("Guess the number: ")) # Converts to integer❌ Modifying a List While Looping Over It
# This can cause unexpected behavior and skipped items.
numbers = [1, 2, 3, 4]
for number in numbers:
if number % 2 == 0:
numbers.remove(number) # DANGEROUS!✅ Loop Over a Copy
# Correct: Loop over a copy to safely modify the original
for number in numbers[:]: # The [:] creates a copy
if number % 2 == 0:
numbers.remove(number)Happy coding! 🐍✨