首页 > 编程语言 > 详细

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

时间:2019-06-13 21:12:32      阅读:139      评论:0      收藏:0      [点我收藏+]

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

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

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

原文:https://www.cnblogs.com/shirley-yang/p/11019433.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!