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

本文详细讲解了Python中for循环的基本用法,包括如何遍历列表、如何使打印结果更具实际意义,以及for循环中代码缩进的重要性。文章还强调了在使用for循环时常见的语法错误,如缩进错误和冒号遗漏。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

转载于:https://www.cnblogs.com/shirley-yang/p/11019433.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值