intermediate Step 8 of 20

Loops - For and While

Python Programming

Loops - For and While

Loops allow you to execute a block of code repeatedly, which is essential for processing collections of data, repeating tasks until a condition is met, and automating repetitive operations. Python provides two types of loops: the for loop for iterating over sequences and iterables, and the while loop for repeating code as long as a condition remains true. Combined with loop control statements like break, continue, and else, Python's loops are both powerful and expressive.

For Loops

# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Using range() for numeric sequences
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)

for i in range(10, 0, -1): # Countdown: 10, 9, 8, ..., 1
    print(i)

# Iterating with index using enumerate()
languages = ["Python", "JavaScript", "Go", "Rust"]
for index, lang in enumerate(languages):
    print(f"{index + 1}. {lang}")

# Iterating over dictionaries
scores = {"Alice": 95, "Bob": 87, "Charlie": 92}
for name, score in scores.items():
    print(f"{name}: {score}")

# Iterating over multiple lists with zip()
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["NYC", "LA", "Chicago"]
for name, age, city in zip(names, ages, cities):
    print(f"{name} is {age} and lives in {city}")

While Loops

# Basic while loop
count = 0
while count < 5:
    print(f"Count: {count}")
    count += 1

# User input loop
while True:
    user_input = input("Enter 'quit' to exit: ")
    if user_input.lower() == "quit":
        break
    print(f"You entered: {user_input}")

# While with condition
import random
target = random.randint(1, 100)
attempts = 0
guess = 0
while guess != target:
    guess = random.randint(1, 100)
    attempts += 1
print(f"Found {target} in {attempts} attempts")

Loop Control Statements

# break — exit the loop immediately
for num in range(100):
    if num > 5:
        break
    print(num)   # Prints 0 through 5

# continue — skip to the next iteration
for num in range(10):
    if num % 2 == 0:
        continue       # Skip even numbers
    print(num)         # Prints 1, 3, 5, 7, 9

# else clause (runs if loop completes without break)
for num in range(2, 10):
    for i in range(2, num):
        if num % i == 0:
            break
    else:
        # This runs only if the inner for loop did NOT break
        print(f"{num} is prime")
# Output: 2 is prime, 3 is prime, 5 is prime, 7 is prime

# Practical: search with for-else
def find_user(users, target_name):
    for user in users:
        if user["name"] == target_name:
            print(f"Found: {user}")
            break
    else:
        print(f"User '{target_name}' not found")

users = [{"name": "Alice"}, {"name": "Bob"}]
find_user(users, "Charlie")  # "User 'Charlie' not found"

Nested Loops and Common Patterns

# Nested loops — multiplication table
for i in range(1, 6):
    for j in range(1, 6):
        print(f"{i*j:4}", end="")
    print()  # New line after each row

# Flattening nested lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = []
for row in matrix:
    for val in row:
        flat.append(val)
print(flat)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Accumulator pattern
numbers = [10, 20, 30, 40, 50]
total = 0
for num in numbers:
    total += num
print(f"Sum: {total}")   # 150

# Building a filtered list
words = ["hello", "world", "hi", "python", "go"]
long_words = []
for word in words:
    if len(word) >= 5:
        long_words.append(word)
print(long_words)  # ['hello', 'world', 'python']
Pro tip: Prefer for loops over while loops when iterating over collections — they are more Pythonic, less error-prone (no risk of infinite loops from forgetting to update the counter), and often more readable. Use enumerate() when you need both the index and value.

Key Takeaways

  • Use for loops to iterate over sequences, ranges, and any iterable; use while for condition-based repetition.
  • range(start, stop, step) generates numeric sequences; enumerate() provides index-value pairs.
  • break exits the loop; continue skips to the next iteration; else runs if the loop completes without break.
  • Use zip() to iterate over multiple sequences in parallel.
  • Avoid infinite while loops by ensuring the condition will eventually become False or using break with a clear exit condition.