一、列表数据的遍历
例:使用for循环来来打印魔术师名单中的所有名字:
magicians.py
magicians = ['alice','david','carolina']
for magician in magicians:
print(magician)
打印结果如下:
alice
david
carolina
建议:编写for循环时,对于用于存储列表中每个值的临时变量,可指定任何名称。然而,选择描述单个列表元素的有意义的名称大有帮助。例如:对于小猫列表、小狗列表和一般性列表,像下面这样编写for循环的第一行代码时不错的选择:
for cat in cats:
for dog in dogs:
for item in list_of_items:
这些命名约定有助于你明白for循环中将对每个元素执行的操作。使用单数和复数式名称,可帮助你判断代码段处理的是单个列表元素还是整个列表。
二、在for循环中执行更多的操作
magicians = ['alice','david','carolina']
for magician in magicians:
print(magcian.title() + ",that was a great trick!")
打印结果如下:
Alice,that was a great trick!
David,that was a great trick!
Carolina,that was a great trick!
注意:Python根据缩进来判断代码行与前一个代码行的关系。在前面的示例中,向各位魔术师显示消息的代码行是for循环的一部分,因为它们缩进了。Python通过使用缩进让代码更易读;简单地说,它要求你使用缩进让代码整洁而结构清晰。在较长的Python程序中,你将看到缩进程度各不相同的代码块。
三、常见的缩进错误及提示信息
(1)magicians.py(应缩进却没有缩进)
magicians = ['alice','david','carolina']
for magician in magicians:
print(magician)
错误提示信息:
File "magicians.py" ,line 3
print(magician)
^
IndentationError: expected an indented block
(2)忘记缩进额外的代码行
magicians = ['alice','david','carolina']
for magician in magicians:
print(magician.title() + ",that was a great trick!")
print("I can't wait to see your next trick, "+ magician.title() + ".\n")
输入结果为:
Alice,that was a great trick!
David,that was a great trick!
Carolina,that was a great trick!
I can't wait to see your next trick,Carolina!
这是一个逻辑错误。从语法上看,这些Python代码时合法的,但由于存在逻辑错误,结果并不符合预期。如果你预期某项操作将针对每个列表元素都执行一次,但它却只执行了一次,请确定是否需要将一行或多行代码缩进。
(3)不必要的缩进
hello_world.py
message = 'Hello Python world!'
print(message)
错误提示信息:
File 'hello_world.py' , line 2
print(message)
^
IndentationError: unexpected indent
提示:为避免意外缩进错误,请只缩进需要缩进的代码。在前面编写的程序中,只有要在for循环中对每个元素执行的代码需要缩进。
(4)遗漏了冒号
for语句末尾的冒号告诉Python,下一行是循环的第一行。
magicians = ['alice','david','carolina']
for magician in magicians
print(magician)
如果你不小心遗漏了冒号,将导致语法错误,因为Python不知道你意欲何为。这种错误虽然易于消除,但并不那么容易发现。程序员为找出这样的单字符错误,花费的时间多的令人惊讶。这样的错误之所以难以发现,是因为通常在我们的意料之外。