Explain For Loops in Python
The for loop in Python is a control flow statement used for iterating over a sequence of elements. This sequence could be a list, tuple, array, or string. It allows you to execute a block of code repeatedly for each item in the sequence.
Syntax
FOR COUNTER IN SEQUENCE:
STATEMENT(S)
Block Diagram
Example
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output
apple
banana
cherry
In this example, the variable fruit takes on each value in the list of fruits in sequence, and the code inside the loop (in this case, print(fruit)) is executed for each value.
Break Statement in for Loop
The Python break statement is used to terminate the loop execution once a specific condition is fulfilled.
Example
# Example of using the break statement
numbers = [1, 2, 3, 4, 5]
# Iterate through the list
for num in numbers:
print(num)
# Check if the number is greater than 3
if num > 3:
# If the condition is met, exit the loop
break
In this example, the loop iterates through the numbers list. When it encounters a number greater than 3, it exits the loop immediately due to the break statement. So, the output will be:
1
2
3
4
Continue Statement in for Loop
The purpose of the continue statement is to bypass the current iteration of a loop and proceed directly to the next iteration.
Example
# Using continue statement to skip odd numbers
for num in range(1, 11):
if num % 2 == 1:
continue # Skip odd numbers
print(num)
Output
2
4
6
8
10
The Range() Function
The range() function in Python facilitates the execution of a set of statements a specified number of times.
Example
# Iterate over a sequence of numbers from 0 to 4
for i in range(5):
print(i)
Output
0
1
2
3
4
This code iterates over the sequence of numbers from 0 to 4 (inclusive) and prints each number in the sequence. When the for structure begins executing, the range() function creates a sequence of values. In this case, the sequence ranges from zero to four.
The first value in this sequence (which is zero) is assigned to the variable x, and then the body of the structure executes.
For each subsequent value in the sequence (1, 2, 3, and 4), the value is assigned to the variable x, and the body of the structure executes again.
This process continues until all values in the sequence have been processed.
So, in each iteration of the loop, the variable x takes on a new value from the sequence created by range(5), and the body of the loop executes with x set to that value. This allows the program to perform operations or execute statements for each value in the sequence.
Else in for Loop
In Python, you can include an else clause after a for loop. This segment is executed if the loop completes its iterations without interruption.
Example:
# Example demonstrating else clause with a for loop
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
else:
print("Loop completed successfully!")
Output
1
2
3
4
5
Loop completed successfully!
In this example, the loop iterates over the list of numbers and prints each number. After all iterations are completed, the else block is executed, printing “Loop completed successfully!”. If the loop is terminated prematurely, the other block will not be executed.
Nested Loops
A nested loop refers to a loop inside another loop. The inner loop executes once for each iteration of the outer loop.
Example
fruits = ["apple", "banana", "orange"]
vegetables = ["carrot", "broccoli", "spinach"]
for fruit in fruits:
for vegetable in vegetables:
print(fruit, "and", vegetable)
Output
apple and carrot
apple and broccoli
apple and spinach
banana and carrot
banana and broccoli
banana and spinach
orange and carrot
orange and broccoli
orange and spinach
Excessive nesting levels can complicate the readability of the program. It’s advisable to limit the use of nested structures to no more than three levels of indentation for better code comprehension.
Access Index in for Loop:
To go through each item in a sequence along with its index number, we can use the enumerate() function.
Example
fruits = ['apple', 'banana', 'cherry', 'date']
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
Output
Index 0: apple
Index 1: banana
Index 2: cherry
Index 3: date
Conclusion
In conclusion, the for loop in Python provides a versatile mechanism for iterating over sequences, with additional features like break, continue, else, and support for nested loops and accessing indices. It’s essential to maintain code readability by avoiding excessive nesting.