Python 3 - Loops
Python 3 - Loops
Section titled “Python 3 - Loops”Normally, Python code executes sequentially from the first statement to the last. However, often you need to repeat a block of code multiple times or execute code based on certain conditions. Control flow structures allow for more complex execution paths.
Loop statements provide a way to execute a block of code repeatedly. This is essential for tasks like processing items in a collection, repeating calculations, or waiting for an event.
Python offers two primary loop constructs:
| Loop Type | Description |
|---|---|
while loop | Repeats a block of code as long as a given condition remains True. The condition is checked before each iteration. |
for loop | Iterates over the items of any sequence (like a list, tuple, string, or range) or other iterable object, executing a block of code once for each item. |
Additionally, loops can be nested, meaning you can place one loop inside another to handle more complex iteration patterns (e.g., iterating over rows and columns in a grid).
The while Loop
Section titled “The while Loop”The while loop repeatedly executes a target statement(s) as long as a given Boolean condition is true.
while condition: # Code block to execute while condition is True statement(s)# Code here runs after the loop finishes (condition becomes False)Example: Counting from 1 to 5
#!/usr/bin/env python3
count = 1while count <= 5: print(f"Count is: {count}") count += 1 # Important: Update the variable used in the condition!
print("Loop finished!")Output:
Count is: 1Count is: 2Count is: 3Count is: 4Count is: 5Loop finished!Warning: Ensure the condition eventually becomes False, otherwise you’ll create an infinite loop.
The for Loop
Section titled “The for Loop”The for loop iterates over items from a sequence (or any iterable). It’s often more convenient than while loops when you know how many times you need to loop or want to process each item in a collection.
for item in iterable: # Code block to execute for each item statement(s)# Code here runs after the loop finishes iterating through all itemsExample: Iterating through a list
#!/usr/bin/env python3
fruits = ["apple", "banana", "cherry"]
print("Available fruits:")for fruit in fruits: print(f"- {fruit.capitalize()}")
print("Loop finished!")Output:
Available fruits:- Apple- Banana- CherryLoop finished!Example: Using range()
The range() function generates a sequence of numbers, commonly used with for loops.
#!/usr/bin/env python3
# Loop 5 times (0 to 4)print("Looping with range(5):")for i in range(5): print(f"Iteration {i}")
# Loop from 2 up to (but not including) 6print("\nLooping with range(2, 6):")for i in range(2, 6): print(f"Iteration {i}")
# Loop from 1 to 10 with a step of 2print("\nLooping with range(1, 10, 2):")for i in range(1, 10, 2): print(f"Iteration {i}")Output:
Looping with range(5):Iteration 0Iteration 1Iteration 2Iteration 3Iteration 4
Looping with range(2, 6):Iteration 2Iteration 3Iteration 4Iteration 5
Looping with range(1, 10, 2):Iteration 1Iteration 3Iteration 5Iteration 7Iteration 9Loop Control Statements
Section titled “Loop Control Statements”Loop control statements alter the normal execution flow within loops:
| Statement | Description |
|---|---|
break | Terminates the current loop prematurely. Execution continues at the first statement after the loop. |
continue | Skips the rest of the current iteration and proceeds to the next iteration of the loop. |
pass | Does nothing. It acts as a placeholder where syntax requires a statement, but no action is needed (e.g., in an empty loop or function body). |
Example using break and continue:
#!/usr/bin/env python3
numbers = [1, 2, 3, -4, 5, 6, -7, 8]
print("Processing numbers:")for num in numbers: if num < 0: print(f"Found negative number {num}, stopping.") break # Exit the loop if num % 2 == 0: print(f"Skipping even number {num}.") continue # Skip to the next number print(f"Processing odd number {num}.")
print("Loop finished or broken.")Output:
Processing numbers:Processing odd number 1.Skipping even number 2.Processing odd number 3.Found negative number -4, stopping.Loop finished or broken.The else Clause in Loops
Section titled “The else Clause in Loops”Python loops (for and while) can have an optional else block. The code in the else block executes only if the loop completes its iterations without encountering a break statement.
#!/usr/bin/env python3
my_list = [1, 3, 5, 7]search_value = 6
for item in my_list: if item == search_value: print(f"Found {search_value}!") breakelse: # This executes only if the loop finished normally (no break) print(f"{search_value} not found in the list.")
search_value = 5for item in my_list: if item == search_value: print(f"Found {search_value}!") breakelse: print(f"{search_value} not found in the list.") # This won't runOutput:
6 not found in the list.Found 5!Iterators and Generators
Section titled “Iterators and Generators”Under the hood, for loops work with iterators. An iterator is an object that allows traversal through a collection (like a list or string) one element at a time. It implements the iterator protocol, which requires __iter__() (returns the iterator object itself) and __next__() (returns the next item or raises StopIteration when exhausted).
You can create an iterator from any iterable using the built-in iter() function and retrieve items using next():
#!/usr/bin/env python3
my_list = [10, 20, 30]it = iter(my_list) # Get an iterator
print(next(it)) # Output: 10print(next(it)) # Output: 20print(next(it)) # Output: 30# print(next(it)) # This would raise StopIteration
# A for loop handles this automatically:print("\nUsing a for loop:")for x in my_list: # Implicitly uses an iterator print(x)A generator is a simpler way to create iterators. It’s defined like a regular function but uses the yield keyword to return values one at a time. When a generator function is called, it returns a generator object (a type of iterator). The function’s execution pauses at yield and resumes from the same point when next() is called again.
Example: Fibonacci sequence generator
#!/usr/bin/env python3
def fibonacci_generator(limit): """Generates Fibonacci numbers up to a limit.""" a, b = 0, 1 while a < limit: yield a a, b = b, a + b
# Get the generator objectfib_gen = fibonacci_generator(50)
print("Fibonacci numbers < 50:")# Iterate through the generator using a for loopfor num in fib_gen: print(num, end=" ") # Output: 0 1 1 2 3 5 8 13 21 34print()Generators are memory-efficient for large sequences because they produce items on demand rather than storing the entire sequence in memory.