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
相關文章
相關標籤/搜索