For Loop
Understanding the For Loop
A for loop in Python is used to iterate over a sequence (like a list, tuple, string, or range) or any other iterable object. It executes a block of code for each item in the sequence.
Syntax
Python
for item in sequence:
# code to be executed for each item
How it Works
1. The for keyword initiates the loop.
2. item is a variable that takes on the value of each element in the sequence during each iteration.
3. The colon : indicates the start of the loop body.
4. The indented code block is executed for each item in the sequence.
Example
Python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
This code will print:
apple
banana
cherry
Iterating over a range
The range() function is often used to generate a sequence of numbers:
Python
for i in range(5):
print(i)
This will print numbers from 0 to 4.
The else Clause (Optional)
The else clause can be used with a for loop. It executes if the loop completes normally (without encountering a break statement).
Python
for num in range(2, 10):
for i in range(2, num):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
Key Points
- Indentation is crucial for defining the loop body.
- The loop variable (e.g., fruit or i in the examples) can be named anything.
- You can use break to exit the loop prematurely and continue to skip the current iteration.
Additional Notes
- For nested loops, the inner loop completes its iterations for each iteration of the outer loop.
- Python also supports enumerate() to get both the index and value of elements in a sequence.
- The zip() function can be used to iterate over multiple sequences in parallel.
For Loop with range() Function
The range() function in Python is commonly used with for loops to iterate over a sequence of numbers. It generates an immutable sequence of numbers and is often used to control the number of times a loop runs.
Syntax
Python
for i in range(start, stop, step):
# code to be executed
Parameters
- start: Optional. The starting number of the sequence. Default is 0.
- stop: Required. The ending number of the sequence (exclusive).
- step: Optional. The difference between each number in the sequence. Default is 1.
Examples
Basic usage:
Python
for i in range(5):
print(i) # Output: 0, 1, 2, 3, 4
Starting from a specific number:
Python
for i in range(2, 10):
print(i) # Output: 2, 3, 4, 5, 6, 7, 8, 9
Using a step value:
Python
for i in range(0, 10, 2):
print(i) # Output: 0, 2, 4, 6, 8
Counting backwards:
Python
for i in range(10, 0, -1):
print(i) # Output: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
Common Use Cases
- Iterating over a specific number of times.
- Creating lists or other data structures.
- Accessing elements in sequences (like lists or strings) by index.
- Implementing algorithms that require repeated calculations.
Important Notes
- The range() function generates a sequence of numbers, but it doesn't create a list in memory. This makes it efficient for large ranges.
- The stop value is exclusive, meaning it's not included in the generated sequence.
- The step value can be negative to create a decreasing sequence.
For Loop with Else
The else clause in Python can be used with a for loop. Unlike the else in an if statement, the else after a for loop executes only when the loop completes normally, without encountering a break statement.
Syntax
Python
for item in sequence:
# code to be executed for each item
else:
# code to be executed if the loop completes normally
How it works
- The for loop iterates over each item in the sequence.
- If the loop completes all iterations without encountering a break statement, the else block is executed.
- If a break statement is encountered within the loop, the else block is skipped.
Example
Python
numbers = [11, 3, 7, 5]
found = False
for num in numbers:
if num % 2 == 0:
found = True
print(num, "is even")
break
if found:
print("At least one even number found.")
else:
print("No even numbers found.")
In this example, the else block will execute only if no even number is found in the list.
Common Use Cases
- Checking if an element exists in a sequence without using in operator.
- Performing actions after a loop completes successfully.
- Optimizing code by avoiding unnecessary checks.
Important Points
- The else block is not executed if the loop is terminated by a break statement.
- The else block is executed even if the loop iterates zero times.
By understanding the for...else construct, you can write more concise and efficient Python code.