In Python, you can use a for
loop to iterate over a sequence of elements, such as a list, tuple, or string. Here’s the basic syntax of a for
loop in Python:
for variable in sequence: # code to be executed for each element in the sequence
The variable
is a new variable that will take on the value of each element in the sequence
during each iteration of the loop. The code within the loop should be indented to show that it belongs to the loop.
Here’s an example of how to use a for
loop to iterate over a list of numbers and print each number:
numbers = [1, 2, 3, 4, 5] for num in numbers: print(num)
Output:
1 2 3 4 5
You can also use the range()
function to generate a sequence of numbers to iterate over. For example:
for i in range(5): print(i) for i in range(5): print(i)
Output:
0 1 2 3 4
In this example, the range(5)
function generates a sequence of five numbers starting from 0 and ending at 4 (not including 5), which is then iterated over in the loop.
You can use a for
loop to iterate over other sequence types as well, such as strings:
message = "Hello, world!" for char in message: print(char)
Output:
H e l l o , w o r l d !
This loop iterates over each character in the string message
and prints it out on a new line.