本文标识 : P00009
本文编辑 : 采药
编程工具 : Python
阅读时长 : 3分钟
很多情况下我们都需要对列表进行遍历操作,下面我们看下,如何对一个魔法师的列表进行遍历:magicians=['alice','avavid','carolina']
for magician in magicians:
print(magician)
看下遍历效果:alice
avavid
carolina
在这里,我们引入了一个循环的概念,它是自动完成重复工作的常见方式之一。
这里我们看下循环中的第一行代码:for magician in magicians:
在这里,我们取列表中的第一个元素‘alice’,并将其存储到变量magician中。然后第二行代码是:print(magician)
这行代码,会打印变量maician的值,由于是第一次执行,所以打印出来的值依然是alice。鉴于列表还包括了其他值,所以python返回到第一行:for magician in magicians:
进行读取下一个值,然后执行第二行第二行代码:print(magician)
一直到列表中的元素打印完毕。
循环操作可以用来干点嘛呢,比如说,我们这里的列表是一组优秀的魔法师,我们需要对他们逐个提出表扬,操作如下:magicians=['alice','avavid','carolina']
for magician in magicians:
print('waitting your next trick, ' + magician + magician.title() + ".\n")
效果如下:waitting your next trick, aliceAlice.
waitting your next trick, avavidAvavid.
waitting your next trick, carolinaCarolina.
循环结束后加一些操作会怎么样?
我们需要知道,for循环后面,没有缩进的代码只执行一次,不会重复执行,下面我们来体验一把:magicians=['alice','avavid','carolina']
for magician in magicians:
print(magician.title() + ",that was a great trick!")
print("I want to see your next trick,"+magician.title()+".\n")
print("Thank you,everyone,That was a great magic show!")
效果如下:Alice,that was a great trick!
I want to see your next trick,Alice.
Avavid,that was a great trick!
I want to see your next trick,Avavid.
Carolina,that was a great trick!
I want to see your next trick,Carolina.
Thank you,everyone,That was a great magic show!
常见错误
需要注意的有两点,第一就是for循环的第一行代码必须有冒号,第二就是缩进,容易忘记或者增加不必要缩进。
1、错误缩进message = "hello Python world"
print(message)
print语句无需缩进,因为它并不属于前一行代码,因此python会指出这种错误:File "", line 1
message = "hello Python world"
^
SyntaxError: invalid character in identifier
2、遗漏冒号magicians=['alice','avavid','carolina']
for magician in magicians:
print(magician)
不小心遗漏冒号,也是会被python指出的,同志们多加注意。File "", line 2
for magician in magicians ^
SyntaxError: invalid syntax