循环的跳出和继续

来源:互联网 发布:淘宝一键复制有违规吗 编辑:程序博客网 时间:2024/04/30 11:02
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。

原创粉丝点击