In Python, the for loop is used to iterate over a sequence (such as a list, tuple, or string) or other iterable object. The basic syntax for a for loop is as follows:
for item in sequence:
# code to be executed for each item in the sequenceHere, item is a variable that takes on the value of each element in the sequence one at a time, and the code inside the loop is executed for each iteration.
You can use the range() function to generate a sequence of numbers for the loop to iterate over. For example:
# Print the numbers from 1 to 10
for i in range(1, 11):
print(i)You can also use the enumerate() function to iterate over a sequence and access both the index and the value of each element. For example:
# Print the index and value of each element in a list
fruits = ['apple', 'banana', 'mango']
for i, fruit in enumerate(fruits):
print(i, fruit)You can use the break statement to exit a for loop prematurely, and the continue statement to skip the rest of the current iteration and move on to the next one.
Here is an example of a for loop that uses these statements:
# Print the numbers from 1 to 10, but skip the number 5
for i in range(1, 11):
if i == 5:
continue
print(i)
# Exit the loop if the number is 8
if i == 8:
breakFor more information on for loops in Python, you can refer to the Python documentation or search online for tutorials and examples.
0 댓글