Chapter 3: Strings and Loops / Lesson 20

For Loops

For Loops

For loops are one of the most powerful and commonly used features in Python. They allow you to iterate over sequences like lists, strings, ranges, and other iterable objects.

For loops are preferred when you know how many times you want to iterate or when you're iterating over a collection of items. They're more Pythonic and often more readable than while loops for these cases.

For Loop with range()

The range() function generates a sequence of numbers, perfect for creating loops that run a specific number of times:

for.py
# Basic range: range(stop) - starts at 0, stops before the number for i in range(5): print(i) # Output: 0, 1, 2, 3, 4 # Range with start and stop: range(start, stop) for i in range(1, 6): print(i) # Output: 1, 2, 3, 4, 5 # Range with step: range(start, stop, step) for i in range(0, 10, 2): print(i) # Output: 0, 2, 4, 6, 8 (even numbers) # Countdown with negative step for i in range(5, 0, -1): print(i) # Output: 5, 4, 3, 2, 1

Iterating Over Sequences

For loops can iterate over any sequence: strings, lists, tuples, and more:

sequences.py
# Iterate over a list fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) # Iterate over a string word = "Python" for char in word: print(char) # Output: P, y, t, h, o, n # Iterate over a tuple coordinates = (10, 20, 30) for coord in coordinates: print(coord)

Using enumerate() for Index and Value

When you need both the index and value, use enumerate():

enumerate.py
fruits = ["apple", "banana", "cherry"] # Get both index and value for index, fruit in enumerate(fruits): print(f"{index}: {fruit}") # Output: # 0: apple # 1: banana # 2: cherry # Start enumeration from a different number for i, fruit in enumerate(fruits, start=1): print(f"{i}. {fruit}")

Loop Control: break and continue

You can control for loops with break (exit) and continue (skip to next iteration):

control.py
numbers = [1, 2, 3, 4, 5] # Break: exit loop early for num in numbers: if num == 4: break print(num) # Output: 1, 2, 3 # Continue: skip current iteration for num in numbers: if num % 2 == 0: continue # Skip even numbers print(num) # Output: 1, 3, 5

Nested For Loops

You can nest for loops to work with multi-dimensional data or create patterns:

nested.py
# Multiplication table for i in range(1, 4): for j in range(1, 4): print(f"{i} × {j} = {i * j}", end=" ") print() # New line after each row # Pattern printing for i in range(1, 5): for j in range(i): print("*", end="") print()

The else Clause in For Loops

For loops can have an else clause that executes after the loop completes normally (not via break):

else_clause.py
numbers = [2, 4, 6, 8] for num in numbers: if num == 5: print("Found 5!") break else: print("5 was not found in the list") # The else runs because break was never executed

Practical Examples

Here are some common real-world uses of for loops:

practical.py
# Sum of numbers numbers = [1, 2, 3, 4, 5] total = 0 for num in numbers: total += num print(f"Sum: {total}") # Find maximum value max_value = numbers[0] for num in numbers: if num > max_value: max_value = num print(f"Maximum: {max_value}") # Process each character in a string text = "Hello" for char in text: print(char.upper())

Range Function Details

💡 Range Function Forms

range(stop) - from 0 to stop-1

range(start, stop) - from start to stop-1

range(start, stop, step) - with step size

💡 Important Notes

• Range is exclusive on the stop value (doesn't include it)

• Range doesn't create a list - it's an iterator (memory efficient)

• To see the values, convert to list: list(range(5))

🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...