Python 循环和条件语句奇怪嵌套

if 在循环体内,else在循环体外,当循环结束且if条件不满足时,执行else语句。

《Python基础教程》5.5.6 循环中的else子句(p82)

1:举例如下(else在循环外,只执行一次):

from math import sqrt
for n in range(99,81,-1):
        root=sqrt(n)
        if root==int(root):
                print n
                break
else:
        print "Didn't find it!"

  运行结果:

Didn't find it!
2:举例如下(else在循环内):
from math import sqrt
for n in range(99,81,-1):
        root=sqrt(n)
        if root==int(root):
                print n
                break
        else:
                print "Didn't find it!"

运行结果:

Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值