Python For Loop

This entry explains what is a Python For Loop and how you can use it in code.

In Python, a for loop is used to iterate over a sequence of elements. The basic syntax of a for loop is as follows:

for variable in sequence:
    # Do something with the variable

Here, variable is a new variable that takes on the value of each element in the sequence on each iteration of the loop. The code inside the loop (indented under the for statement) is executed once for each element in the sequence.

Looping over a range of numbers

You can use the range() function to generate a sequence of numbers to iterate over. Here’s an example:

# Loop from 1 to 5
for i in range(1, 6):
    print(i)

This code will print the numbers 1 to 5, inclusive.

Looping over a string

You can use a for loop to iterate over the characters in a string. Here’s an example:

# Loop over the characters in a string
word = "hello"
for letter in word:
    print(letter)

This code will print each character of the string “hello” on a separate line.

Looping over a list

For example, consider the following code:

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

In this code, we define a list of fruits and then use a for loop to iterate over the elements of the list. On each iteration of the loop, the fruit variable takes on the value of the current fruit in the list and the print statement is executed with that value. The output of this code would be:

apple
banana
cherry

Looping over a list of lists

You can use nested for loops to iterate over a list of lists. Here’s an example:

# Loop over a list of lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
    for value in row:
        print(value)

This code will print each value in the matrix on a separate line.

Looping over a dictionary

You can use a for loop to iterate over the keys or values in a dictionary. Here are a few examples:

# Loop over the keys in a dictionary
ages = {"Alice": 25, "Bob": 30, "Charlie": 35}
for name in ages:
    print(name)

# Loop over the values in a dictionary
for age in ages.values():
    print(age)

# Loop over the key-value pairs in a dictionary
for name, age in ages.items():
    print(f"{name} is {age} years old")

The first loop will print the keys in the dictionary, the second loop will print the values, and the third loop will print each key-value pair.

These are just a few examples of the many ways you can use for loops in Python to iterate over different types of sequences and data structures.