Python For Loops

In Python, a "for loop" is a control flow structure that allows you to iterate over a sequence (such as a list, tuple, string, or range) and perform a set of statements for each item in that sequence. This loop is particularly useful when you want to repeat a specific block of code a fixed number of times or when you want to process each element in a collection, performing some action on each item.

Here's the basic syntax of a for loop in Python:

        
for variable in sequence:
    # code to be executed for each item in the sequence
        
    

- variable: This is a variable that takes on the value of each item in the sequence during each iteration of the loop.

- sequence: This is the sequence over which the loop iterates, such as a list, tuple, string, or range.

Let's go through some examples to illustrate how for loops work:

Example 1: Iterating over a List

        
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
        
    

In this example, the for loop iterates through the fruits list and assigns each item to the fruit variable. The loop then prints each fruit to the console.

Example 2: Iterating over a Range

        
for i in range(5):
    print(i)
        
    

Here, the range(5) function generates a sequence of numbers from 0 to 4. The for loop iterates through this sequence and prints each number.

Example 3: Iterating over a String

        
message = "Hello, World!"
for character in message:
    print(character)
        
    

This loop iterates over each character in the message string and prints each character.

Example 4: Using enumerate for Index and Value

        
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")
        
    

In this example, enumerate is used to iterate through the fruits list while keeping track of the index and the value. It prints both the index and the fruit.

Example 5: Using break and continue

        
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num == 3:
        break  # Exit the loop when num is 3
    if num == 2:
        continue  # Skip the iteration when num is 2
    print(num)
        
    

You can use the break statement to exit the loop prematurely and the continue statement to skip the current iteration and move to the next one. For example, this loop will print 1 and exit when num is 3, and it will skip 2 using continue.

For loops are versatile and can be used in various scenarios to perform repetitive tasks, process data, or iterate through collections, making them a fundamental part of Python programming.