while 循環(huán)
Python中while語句的一般形式
while 判斷條件:
語句
while 有限循環(huán)
n = 100
sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
print("1 到 %d 之和為: %d" % (n,sum))
while 無限循環(huán)
我們可以通過設(shè)置條件表達式永遠不為 false 來實現(xiàn)無限循環(huán),實例如下:
var = 1
while var == 1 : # 表達式永遠為 true
num = int(input("輸入一個數(shù)字 :"))
print ("你輸入的數(shù)字是: ", num)
print ("Good bye!")
你可以使用 CTRL+C 來退出當(dāng)前的無限循環(huán)。
while 循環(huán)使用 else 語句
在 while … else 在條件語句為 false 時執(zhí)行 else 的語句塊:
count = 0
while count < 5:
print (count, " 小于 5")
count = count + 1
else:
print (count, " 大于或等于 5")
while 簡單語句組
類似if語句的語法,如果你的while循環(huán)體中只有一條語句,你可以將該語句與while寫在同一行中, 如下所示:
flag = 1
while (flag): print ('歡迎訪問菜鳥教程!')
print ("Good bye!")
for 語句
Python for循環(huán)可以遍歷任何序列的項目,如一個列表或者一個字符串。
for循環(huán)的一般格式如下:
sites = ["Baidu", "Google","Runoob","Taobao"]
for site in sites:
if site == "Runoob":
print("菜鳥教程!")
break
print("循環(huán)數(shù)據(jù) " + site)
else:
print("沒有循環(huán)數(shù)據(jù)!")
print("完成循環(huán)!")
break 語句 在語句塊執(zhí)行過程中終止循環(huán),并且跳出整個循環(huán)
continue 語句 在語句塊執(zhí)行過程中終止當(dāng)前循環(huán),跳出該次循環(huán),執(zhí)行下一次循環(huán)。
pass 語句 pass是空語句,是為了保持程序結(jié)構(gòu)的完整性。
range()函數(shù)
如果你需要遍歷數(shù)字序列,可以使用內(nèi)置range()函數(shù)。它會生成數(shù)列,例如:
for i in range(0, 10, 3) :
for i in range(5,9) :
for i in range(-10, -100, -30) :
a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ']
for i in range(len(a)):
print(i, a[i])
Fibonacci series: 斐波納契數(shù)列 兩個元素的總和確定了下一個數(shù)
a, b = 0, 1
while b < 1000:
print(b, end=',')
a, b = b, a+b
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
