while循環(huán)
只要循環(huán)條件為True(以下例子為x > y),while循環(huán)就會一直 執(zhí)行下去:
u, v, x, y = 0, 0, 100, 30 ⇽--- ❶ while x > y: ❷ u = u + y x = x - y if x < y + 2: v = v + x x = 0 else: v = v + y + 2 x = x - y - 2 print(u, v)
上面用到了一個簡寫記法,u和v被賦值為0,x被設(shè)置為100,y的 值則成為30❶。接下來是循環(huán)代碼塊❷,循環(huán)可能包含break(退出循 環(huán))和continue語句(中止循環(huán)的本次迭代)。輸出結(jié)果將會是60 40。
for循環(huán)
for循環(huán)可以遍歷所有可迭代類型,例如列表和元組,因此既簡單 又強大。與許多其他語言不同,Python的for循環(huán)遍歷的是序列(如列 表或元組)中的每一個數(shù)據(jù)項,使其更像是一個foreach循環(huán)。下面的循環(huán),將會找到第一個可以被7整除的整數(shù):
item_list = [3, "string1", 23, 14.0, "string2", 49, 64, 70] for x in item_list: ⇽--- ❶ if not isinstance(x, int): continue ⇽--- ❷ if not x % 7: print("found an integer divisible by seven: %d" % x) break ⇽--- ❸
x依次被賦予列表中的每個值❶。如果x不是整數(shù),則用continue 語句跳過本次迭代的其余語句。程序繼續(xù)流轉(zhuǎn),x被設(shè)為列表的下一項 ❷。當(dāng)找到第一個符合條件的整數(shù)后,循環(huán)由break語句結(jié)束❸。輸出 結(jié)果將會是:
found an integer divisible by seven: 49
上面就是關(guān)于while和for循環(huán)的全部知識點,感謝大家的學(xué)習(xí)和對武林站長站的支持。
新聞熱點
疑難解答