Python For Loop

The for loop in Python is used to iterate over elements of a sequence (like a list, tuple, string, etc.) or other iterable objects. It allows us to execute a block of code repeatedly for each item in the sequence.

Syntex:

for item in sequence:
    # Loop body

Here, item represents each element in the sequence during each iteration.

Example 1: Sum of Squares

This example calculates the sum of the squares of each element in a list.

# Creating the list of numbers
numbers = [3, 5, 2, 8]

# Initializing a variable to store the sum
sumOfSquare = 0

# Using for loop to iterate over the list
for num in numbers:
    sumOfSquare += num ** 2

print("The sum of squares is:", sumOfSquare)

Output:

The sum of squares is: 107

Example 2: Using range() Function

The range() function generates a sequence of numbers, which is often used in for loops to repeat actions a specific number of times.

squares = []

# Using range() function with for loop
for i in range(5):
    squares.append(i ** 2)

print("List of squares:", squares)

Output:

List of squares: [0, 1, 4, 9, 16]

Example 3: Iterating Using Index

This example demonstrates iterating through a list using indices.

# Creating the list of numbers
numbers = [10, 20, 30, 40]

# Initializing a variable to store the sum
totalSum = 0

# Using for loop with range() to iterate by index
for i in range(len(numbers)):
    totalSum += numbers[i]

print("The total sum is:", totalSum)

Output:

The total sum is: 100

Example 4: Using else with for Loop

The else block executes after the for loop has finished iterating over the sequence, but only if the loop is not terminated by a break statement.

numbers = [1, 2, 3, 4, 5]
searchNum = 3

for num in numbers:
    if num == searchNum:
        print(f"{searchNum} found in the list.")
        break
else:
    print(f"{searchNum} not found in the list.")

Output:

3 found in the list.

Example 5: Nested Loops

Nested loops involve placing one loop inside another. This is useful for tasks like matrix operations.

rows = 5
cols = 5

# Outer loop for rows
for i in range(1, rows + 1):
    # Inner loop for columns
    for j in range(1, cols + 1):
        # Print the product of the current row and column
        print(i * j, end='\t') # `end='\t'` keeps the output on the same line separated by tabs
    print() # Print a new line after each row

Output:

1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25