Python中遍历整个列表及注意点(参考书籍Python编程从入门到实践)

Python publisher01 34℃

1. 利用for循环遍历整个列表

magicians = ['alice', 'dsvid', 'carolina']
# 遍历整个列表
for magician in magicians:
print(magician)

2. 使得打印结果变得更加有实际意义

for magician in magicians:
print(magician.title() + ', that was a great trick!')
运行结果:
Alice, that was a great trick!
Dsvid, that was a great trick!
Carolina, that was a great trick!

for代码行后边缩进的代码块都是循环的一部分,继续增加打印语句:

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")
运行结果:

 

3. 对于for循环后边的属于循环模块的代码行一定要缩进。

3.1 若没有缩进:

for magician in magicians:
print(magician.title() + ', that was a great trick!')


运行结果会报错:

IndentationError: expected an indented block

 

3.2 若有缩进的有没有缩进的:

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!
Dsvid, that was a great trick!
Carolina, that was a great trick!
I can’t wait to see your next trick, Carolina

 

3.3 若缩进了本应在循环结束之后执行的代码,则这些代码将针对每个元素循环执行一次,程序不会报错。

 

4. 对于for循环还要注意的一点是——for语句的末尾千万不要忘了冒号(太容易忘了,太容易忘了,太容易忘了。。。)。

一旦忘记冒号,程序运行就会报错: