当前位置: 移动技术网 > IT编程>脚本编程>Python > Python中遍历整个列表及注意点(参考书籍Python编程从入门到实践)

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

2019年06月14日  | 移动技术网IT编程  | 我要评论

徐湘婷资料,北之星冠,总裁爹地请小心

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网