A for loop in Python is a control flow statement that allows you to iterate over a sequence of values, such as a list, tuple, or string, and perform a set of instructions for each element of the sequence.
The basic syntax of a for loop in Python is as follows:
for element in sequence: # do something with element
Here, element
is a variable that represents the current element of the sequence being processed, and sequence
is the sequence of values being iterated over. The :
character is used to indicate the start of a new block of code, which is executed for each element of the sequence.
Let’s look at an example that demonstrates how to use a for loop to iterate over a list of numbers and print each element:
numbers = [1, 2, 3, 4, 5] for num in numbers: print(num)
Output:
1 2 3 4 5
In this example, numbers
is a list of integers, and the for
loop iterates over each element in the list and assigns it to the variable num
. The print()
function is then called to output the value of num
to the console.
You can also use the range()
function with a for loop to iterate over a range of numbers. For example:
# Example 1 for i in range(5): print(i) # Output: 0 1 2 3 4 # Example 2 for i in range(1, 10, 2): print(i) # Output: 1 3 5 7 9
In the first example, range(5)
generates a sequence of numbers starting from 0 and ending at 4 (not including 5), and the for loop iterates over this sequence and prints each number.
In the second example, range(1, 10, 2)
generates a sequence of odd numbers starting from 1 and ending at 9 (not including 10), and the for loop iterates over this sequence and prints each number.