for
In programming, the for loop is used to iterate over a sequence of elements (such as a list or a string) and execute a block of code for each element.
The syntax for a for loop in Python is as follows:
for element in sequence:
# code to be executed for each element
Here, element is a variable that takes on the value of each element in the sequence one at a time, and sequence is a sequence of elements (such as a list or a string). The for loop will iterate over each element in the sequence in turn, and the code inside the loop will be executed for each element.
Here is an example of how you can use a for loop in Python:
for number in [1, 2, 3, 4, 5]:
print(number)
This for loop will iterate over the elements in the list [1, 2, 3, 4, 5] and print each element. The output of this code will be:
1
2
3
4
5
You can also use the range() function in combination with a for loop to iterate over a range of numbers. 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.
Here is an example of how you can use the range() function in a for loop:
for number in range(5):
print(number)
This for loop will iterate over the numbers 0, 1, 2, 3, and 4 (since the range() function ends at 5), and print each number. The output of this code will be:
0
1
2
3
4
You can also specify a starting number and a step size for the range() function. For example:
for number in range(2, 6, 2):
print(number)
This for loop will iterate over the numbers 2, 4 (since the range() function ends at 6 and increments by 2), and print each number. The output of this code will be:
2
4
You can use the break statement inside a for loop to exit the loop early, and the continue statement to skip the rest of the current iteration and move on to the next one.