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