欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-22 12:55:22
1. 利用for循环遍历整个列表 2. 使得打印结果变得更加有实际意义 3. 对于for循环后边的属于循环模块的代码行一定要缩进。 3.1 若没有缩进: for magician in magicians:print(magician.title() + ', that was a great tr ......

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")
运行结果:
Python中遍历整个列表及注意点(参考书籍Python编程从入门到实践)
 

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语句的末尾千万不要忘了冒号(太容易忘了,太容易忘了,太容易忘了。。。)。

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