- 用for循环遍历整个列表。
- for语句末尾有一个冒号。
- 在for循环中,可以给与列表中的每个值关联的临时变量指定任意名称,但是选择描述单个列表的有意义的名称是好的实践。例如,列表名称用复数hobbies,而跟列表中的每个值关联的临时变量用单数hobby 。
- 位于for语句后面且属于循环组成部分的代码行,一定记着缩进。python是根据缩进来判断代码行与前一行代码的关系。
例如:
hobbies = ['travelling', 'reading', 'eating', 'running']
for hobby in hobbies:
print(f'{hobby.title()} is a good hobby.')
print()
print("It's the end.")
运行输出:
Travelling is a good hobby.
Reading is a good hobby.
Eating is a good hobby.
Running is a good hobby.
It's the end.