循环的跳出和继续

1.break 终止。它在while True语句中经常应用。
from math import sqrt
for n in range(99,0,-1):
    root=sqrt(n)
    if root==int(root):
        print n
        break
会输出81,这个是求最大平方数,引入了数学库中的sqrt,求平方根。range这个里面有第三个参数,步长,和分片里面的很相似,这个是往下迭代。root就是求的根。if root ==int(root),即是如果这个根是整数。

2.continue
这个语句比break用的要少的多,他是跳出当前的循环体,进入到下一个循环中,但是这不是结束这个循环。这在某些情况下会使用,比如当循环体很大的时候,因为一些原因先跳过这个循环,    这个时候就可以使用这个continue。
for x in seq:
    if condition1:continue
    if condition2:continue
    if condition3:continue

    do_something()
    do_something_else()
    do_anotherthing()
    etc()

这些也是不必要的,可以改写为下面的东西。
for x in seq:
    if not (condition1 or condition2 or condition3):
        
    do_something()
            do_something_else()
            do_anotherthing()
            etc()

3.while True
先看一个我们经常用的:
word='wang'
while word:
    word=raw_input('please enter a word: ')
    print 'the word is ' +word

结果:
please enter a word: WANG
the word is WANG
please enter a word:

这个代码完成了工作,下面还是要输入词。代码不美观。这个时候,可以用while True
while True:
    word=raw_input('please enter a word: ')
    if not word:break
    print 'the word is '+word

这个和上面的结果一模一样,也实现了永远也不停的循环。这个分为两个部分,在break之前是一个部分,在后面又是一个部分。仔细分析,前面的是初始化,后面的是调用它的值。

4.循环里的else语句
看个例子就明白了:
from math import sqrt
for n in range(99,81,-1):
    root=sqrt(n)
    if root==int(root):
        print n
else:
    print 'it is not in the range'

它的结果是:
it is not in the range
在print n的后面没有加break,结果也是一样的。看来都差不多。
for 和while都可以在循环中使用break,continue,else。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值