Python while循環(huán)是在滿足一定條件時反復執(zhí)行某一語句塊,直到條件值為假為止。
while 循環(huán)條件:
# 循環(huán)體語句
程序執(zhí)行到while循環(huán)時:
(1)先判斷條件是否為True;
(2)如果為True,則執(zhí)行循環(huán)體中的語句;
(3)如果為False,則執(zhí)行循環(huán)體后邊的其它語句;
(4)執(zhí)行完一次循環(huán)體后,再次判斷條件,進入(2)。
1、使用while循環(huán)計算1~100所有數(shù)字的和。
i = 1
sum = 0
while i <= 100:
sum += i
i += 1
print("i={0},sum={1}".format(i, sum))
輸出結果:
i=101,sum=5050
2、使用while循環(huán)輸出50以內的偶數(shù)
i = 1
n = 100
while i <=100:
if i % 2 == 0:
print(i)
i += 1
3、while和else結合使用
while可以else結合起來使用,當while條件不滿足時,則執(zhí)行else中的內容
x = input("請輸入一個整數(shù):")
x = int(x)
i, s = 1, 0
while i < x:
s += i
i += 1
else:
print("執(zhí)行完畢。")
print("1到{}的所有數(shù)字之和為:{}".format(x, s))
輸出結果:
請輸入一個整數(shù):10
執(zhí)行完畢。
1到10的所有數(shù)字之和為:45
本文(完)
新聞熱點
疑難解答
圖片精選