Python while循环

while循环语法结构

当需要语句不断的重复执行时,可以使用while循环
while expression:
    while_suite
语句while_suite会连续不断的循环执行,直到表达式的值变成0或false
 
#!/usr/bin/env python

sum100 = 0
counter = 1

while counter <= 100:
    sum100 += counter
    counter += 1

print "result is %d" % sum100

break语句

break语句可以结束当前循环然后跳转到下条语句
写程序的时候,应尽量避免重复的代码,在这种情况下可以使用while-break结构
#!/usr/bin/env python

while True:
    yn = raw_input("continue?(y/n)")
    if yn in 'Yy':
        break
    print "work on"

/usr/bin/python2.6 /root/PycharmProjects/untitled10/break1.py
continue?(y/n)n
work on
continue?(y/n)y

Process finished with exit code 0

continue语句

当遇到continue语句时,程序会终止当前循环,并忽略剩余的语句.然后回到循环的顶端
如果仍然满足循环条件,循环体内语句继续执行,否则退出循环
所有偶数的和
#!/usr/bin/env python

sum100 = 0
counter = 1

while counter <= 100:
    counter += 1
    if counter % 2 == 1:
        continue
    sum100 += counter
print sum100

else语句

python中的while语句也支持else子句
else子句只在循环完成后执行
break语句也会跳过else块
#!/usr/bin/env python

sum10 = 0
i = 1

while i <= 10:
    sum10 += i
    i += 1
else:
    print sum10

 

posted @ 2017-03-15 10:57  Time.catcher  阅读(7962)  评论(0编辑  收藏  举报