September 11, 2024

How to Use a For Loop in Python

The for loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) or other iterable objects. It allows you to execute a block of code repeatedly for each item in the sequence. Below are some examples and common use cases for the for loop in Python.

1. Basic Syntax of the for Loop

The basic syntax of a for loop in Python is as follows:

for variable in sequence:
    # Code to execute

Here, variable takes the value of each item in the sequence on each iteration, and the block of code within the loop is executed once for each item.

2. Iterating Over a List

One of the most common uses of a for loop is to iterate over a list of items.

Example:

# Iterating over a list
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry

In this example, the loop iterates over the list fruits, and each item in the list is printed on a new line.

3. Iterating Over a String

You can also use a for loop to iterate over the characters in a string.

Example:

# Iterating over a string
for letter in "Python":
    print(letter)

Output:

P
y
t
h
o
n

In this example, each character in the string “Python” is printed on a new line.

4. Iterating Over a Range of Numbers

The range() function generates a sequence of numbers, which can be used with a for loop to iterate over a specific range.

Example:

# Iterating over a range of numbers
for i in range(5):
    print(i)

Output:

0
1
2
3
4

In this example, the loop iterates over the numbers from 0 to 4 (inclusive), printing each number.

5. Using break in a For Loop

The break statement can be used to exit a for loop prematurely when a certain condition is met.

Example:

# Using break to exit a loop
for i in range(10):
    if i == 5:
        break
    print(i)

Output:

0
1
2
3
4

In this example, the loop stops when i equals 5, so the numbers 0 through 4 are printed.

6. Using continue in a For Loop

The continue statement can be used to skip the rest of the code inside the loop for the current iteration and move on to the next iteration.

Example:

# Using continue to skip an iteration
for i in range(5):
    if i == 2:
        continue
    print(i)

Output:

0
1
3
4

In this example, the number 2 is skipped, so the loop prints all numbers except 2.

7. Using else with a For Loop

An optional else block can be used with a for loop. The code inside the else block is executed after the loop finishes, unless the loop is terminated by a break statement.

Example:

# Using else with a for loop
for i in range(5):
    print(i)
else:
    print("Loop is complete.")

Output:

0
1
2
3
4
Loop is complete.

In this example, the else block is executed after the loop completes normally.

8. Nested For Loops

A for loop can be nested inside another for loop. This is useful when you need to iterate over a sequence within another sequence.

Example:

# Nested for loops
for i in range(3):
    for j in range(2):
        print(f"i = {i}, j = {j}")

Output:

i = 0, j = 0
i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
i = 2, j = 1

In this example, the outer loop iterates over the range 0 to 2, and for each iteration of the outer loop, the inner loop iterates over the range 0 to 1.

The for loop in Python is a versatile and powerful tool for iterating over sequences and other iterable objects. By understanding its various use cases, such as iterating over lists, strings, ranges, and using control statements like break and continue, you can effectively manage loops in your Python programs.