► Overview
For loops allow you to repeat code a specific number of times or iterate through items in a collection. They are essential for automating repetitive tasks.
► Real-World Analogy
Think of a for loop like reading a book:
» For each page in the book
» Read the page
» Turn to next page
» Repeat until book is finished
► Key Concepts
✓ Iteration: Repeating a process multiple times
✓ range(): Generates sequence of numbers
✓ Loop Variable: Tracks current iteration
✓ Iterable: Object you can loop through (list, string, etc.)
■ For Loop Examples
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# Simple for loop with range() for i in range(5): print("Iteration:", i) # Loop through a list fruits = ["apple", "banana", "cherry"] for fruit in fruits: print("I like", fruit) # Using enumerate to get index and value colors = ["red", "green", "blue"] for index, color in enumerate(colors): print(f"Color {index}: {color}") Output: Iteration: 0 Iteration: 1 Iteration: 2 Iteration: 3 Iteration: 4 I like apple I like banana I like cherry Color 0: red Color 1: green Color 2: blue ► Important Points ✓ For loops are perfect for iterating over sequences ✓ range() is commonly used to generate numbers ✓ Loop variable automatically updates each iteration ✓ Works with lists, strings, tuples, and more ✓ More efficient than manual counting ► Remember ✓ Indentation defines the loop body ✓ range(n) goes from 0 to n-1 ✓ You can loop through any iterable object ✓ Use meaningful loop variable names ■ Practice Challenge 1. Create a for loop that prints numbers from 1 to 10 2. Write a loop that prints each character in your name 3. Create a loop that calculates sum of numbers from 1 to 100 |
