Python For Loop

A for loop in Python allows you to iterate over a sequence of elements, such as a list or a string. It allows you to execute a block of code for each element in the sequence. Here’s the syntax for a for loop in Python:

for element in sequence:
    # code block to be executed

The for loop begins with the for keyword, followed by an element variable (which you can choose the name of), the in keyword, and the sequence you want to iterate over. The element variable is used to represent each element in the sequence as the loop iterates over it. The code block that follows is indented, and this is where you can specify the actions you want to be performed on each element in the sequence. For example, consider the following list of integers:

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

If we wanted to print out each element in this list, we could use a for loop like this:

for number in numbers:
    print(number)

This would print the following output:

1
2
3
4
5

You can use the for loop to iterate over any sequence in Python, including strings. For example:

for char in "Hello":
    print(char)

This would print the following output:

H
e
l
l
o

You can also use the for loop to execute a certain number of iterations by using the range function. The range function returns a sequence of numbers, starting from 0 by default, and increments by 1 (also by default), and ends at a specified number.

For example, to execute a for loop 10 times, you could use the following code:

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

This would print the numbers 0 through 9. I hope this explanation helps! Let me know if you have any questions.

Was this helpful?
[0]