Python For Loop: Complete Guide with Examples

The basic syntax for a for loop statement in Python is as follows:

for 变量 in 序列:
    执行的代码块

The variable in this case refers to the variable in the loop, and the sequence can be a list, tuple, string, or any other iterable object. During each iteration of the loop, the variable will sequentially take each element from the sequence and then execute the code block.

Here is a simple example of a for loop:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

This code will print out each element in the fruits list in order.

In addition to the basic for loop statement, Python also offers some convenient functions and syntax sugars, such as the range() function and list comprehensions, which allow for more flexible use of for loops.

bannerAds