Python For Loop: A Complete Guide with Examples
In Python, the for loop is used to iterate through elements in iterable objects such as lists, tuples, strings, etc.
The basic syntax of a for loop is as follows:
for 元素 in 可迭代对象:
执行代码块
In each iteration, the iterable object contains multiple elements, where each loop iteration will fetch one element from the object and assign it to the variable “element”. The code within the block will be executed during each iteration.
For example, looping through the elements of a list:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Different operations, such as calculations, evaluations, and list manipulations, can be performed as needed within the loop.
In addition to the basic for loop syntax, Python also offers some related keywords and functions such as the range() function, enumerate() function, break keyword, and continue keyword for more flexible control over loop behavior.