Loops are control flow statements that allow you to repeatedly execute a block of code. This is incredibly useful for iterating over collections of items or performing actions a fixed number of times. Python's primary loop for iteration is the for loop.
The for Loop
The for loop is used to iterate over a sequence (like a string, list, tuple, or dictionary) or other iterable objects. It executes a block of code once for each item in the sequence.
Syntax:
pythonfor variable_name in sequence: # Code to execute for each item statement_1 statement_2
Example 1: Iterating over a string
pythonword = "Python" for char in word: print(char) # Output: # P # y # t # h # o # n
Example 2: Iterating over a list (will cover lists in more detail later)
pythonfruits = ["apple", "banana", "cherry"] for fruit in fruits: print(f"I like {fruit}.") # Output: # I like apple. # I like banana. # I like cherry.
The range() Function
The range() function is often used with for loops to generate a sequence of numbers. It's particularly useful when you want to loop a specific number of times.
Syntax:
range(stop): Generates numbers from 0 up to (but not including)stop.range(start, stop): Generates numbers fromstartup to (but not including)stop.range(start, stop, step): Generates numbers fromstartup to (but not including)stop, incrementing bystep.
Example 1: Loop a fixed number of times (0 to 4)
pythonfor i in range(5): print(i) # Output: # 0 # 1 # 2 # 3 # 4
Example 2: Loop from a specific start number (2 to 6)
pythonfor j in range(2, 7): print(j) # Output: # 2 # 3 # 4 # 5 # 6
Example 3: Loop with a step (0, 2, 4, 6, 8)
pythonfor k in range(0, 10, 2): print(k) # Output: # 0 # 2 # 4 # 6 # 8
Example 4: Looping backwards (countdown)
pythonfor countdown in range(5, 0, -1): print(countdown) print("Blast off!") # Output: # 5 # 4 # 3 # 2 # 1 # Blast off!
Combining for with if
You can combine for loops with if statements to perform conditional actions within a loop.
pythonnumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for num in numbers: if num % 2 == 0: # Check if number is even print(f"{num} is even.") else: print(f"{num} is odd.") # Output: # 1 is odd. # 2 is even. # ...
The for loop and range() function are indispensable tools for automating repetitive tasks and processing collections of data. They form a core part of Python's control flow mechanisms.
Key Takeaways:
forloops iterate over sequences (strings, lists, etc.) or other iterable objects.- The code block inside the loop executes once for each item in the sequence.
range()generates a sequence of numbers, commonly used to control the number of loop iterations.range()can take one (stop), two (start, stop), or three (start, stop, step) arguments.- Loops can be combined with conditional statements for more complex logic.