Python Loops
Python Loops
Section titled “Python Loops”In programming, we often need to execute a block of code multiple times. Instead of writing the same code repeatedly, we use loops.
Loops are control structures that allow for repeated execution of a code block based on a condition or by iterating over a sequence.
Conceptual Flow of a Loop:
- Check a condition or get the next item from a sequence.
- If the condition is true or items remain: Execute the loop body.
- Go back to step 1.
- If the condition is false or no items remain: Exit the loop and continue with the code after the loop.
Python provides two primary types of loops:
| Loop Type | Description |
|---|---|
| while loop | Repeats a block of code as long as a given condition remains True. The condition is tested before each execution of the loop body. |
| 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. |
| nested loops | You can place one loop inside another. This is useful for working with multi-dimensional data structures or complex iteration patterns. |
Note: Python does not have a do..while loop construct found in some other languages, where the loop body is guaranteed to execute at least once before the condition is checked.
Loop Control Statements
Section titled “Loop Control Statements”Loop control statements alter the normal execution flow within loops:
Python supports the following control statements:
| Control Statement | Description |
|---|---|
| break statement | Immediately terminates the current loop (the innermost loop if nested) and transfers execution to the statement following the loop. |
| continue statement | Skips the rest of the code inside the current iteration of the loop and proceeds to the next iteration (re-evaluating the condition in a while loop or getting the next item in a for loop). |
| pass statement | Acts as a null operation. It’s used when a statement is syntactically required but you don’t want any command or code to execute. It’s often used as a placeholder during development. |
Example: while loop
Section titled “Example: while loop”count = 0while count < 5: print(f"Count is: {count}") count += 1 # Important: Increment counter to avoid infinite loop
print("Loop finished!")Example: for loop with range
Section titled “Example: for loop with range”for i in range(3): # range(3) generates numbers 0, 1, 2 print(f"Iteration {i}")
print("Loop finished!")Example: for loop with a list
Section titled “Example: for loop with a list”fruits = ["apple", "banana", "cherry"]for fruit in fruits: print(f"Current fruit: {fruit}")
print("Loop finished!")Example: break statement
Section titled “Example: break statement”for i in range(10): if i == 5: print("Breaking loop") break # Exit the loop when i is 5 print(f"i = {i}")
print("After the loop")Example: continue statement
Section titled “Example: continue statement”for i in range(5): if i == 2: print("Skipping iteration 2") continue # Skip the rest of this iteration print(f"Processing i = {i}")
print("After the loop")