In Python, a for loop is a programming construct that allows you to iterate over a sequence of values and perform an action for each value in the sequence. The general syntax of a for loop in Python is as follows:
for variable in sequence:
# Code to be executed for each value in the sequence
In this syntax, variable
is a variable that will take on the value of each item in the sequence
. The sequence
can be any iterable object such as a list, tuple, or string. The code inside the loop, which is indented, will be executed for each item in the sequence.
Here's an example of a for loop that iterates over a list of numbers and prints each number:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
This will 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)
This will output:
0 1 2 3 4
In addition, you can use the break
and continue
statements inside a for loop to control the flow of execution. The break
statement will exit the loop entirely, while the continue
statement will skip the rest of the current iteration and move on to the next item in the sequence.
Comments
Post a Comment