A for loop in Python is used to iterate through a sequence of elements. The general syntax of a for loop in Python is:

for variable in sequence:
    # code to be executed for each element in the sequence

Here, variable is a placeholder for each element in the sequence, and sequence can be any iterable object such as a list, tuple, string, or dictionary.

For example, let's say we have a list of numbers and we want to print each one:

numbers = [1, 2, 3, 4, 5]
for n in numbers:
    print(n)

This will output:

1
2
3
4
5

You can also use the range() function to generate a sequence of numbers:

for i in range(1, 6):
    print(i)

This will output the same result as above.

You can also loop through a dictionary using the items() method, which returns key-value pairs:

person = {'name': 'Alice', 'age': 25, 'gender': 'female'}
for key, value in person.items():
    print(key, value)

This will output:

name Alice
age 25
gender female
python for loop

原文地址: https://www.cveoy.top/t/topic/bcVA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录