Python小知识:else除了跟if很搭,你还知道其他的关键词吗?

用Python这么久了,只知道else与if很搭,其实跟else关系很好的关键词还有while、for。

一、while

1.1 最基本的while循环

while condition:
    statements

只要condition条件是True,程序就执行while代码块中的statements。例如:

restrict = 5
index = 1

while index<restrict:    print('{}<{}'.format(index,restrict))    index+=1
1<5
2<5
3<5
4<5

1.2 带else的while循环

大家都知道if_else,我一直以为python的世界里只有if才和else很配,没想到while也可以这么写。貌似很少看到这种写法

while conditon:
    statement1
else:
    statement2

例如

restrict = 5
index = 1

while index<restrict:    print('{}<{}'.format(index,restrict))    index+=1
else:    print('程序结束')
1<5
2<5
3<5
4<5
程序结束

需要注意一点,当while中break之后,else里的指令就不会再执行

二、for循环

2.1 最简单的for

for item in iterable_obj:
    statements

2.2 for_else

真没想到,if、while和for都能跟else搭配使用!

for item in iterable_obj:
    statement1
else:    statement2

例如

fruits = ["banana", "apple", "orange", "kiwi"]

for food in fruits:    print(food)
else:    print("reached end of list")
banana
apple
orange
kiwi
reached end of list
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

魔都飘雪

您的1毛奖励是我创作的源源动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值