while 判斷條件:
迴圈內第一行程式碼
迴圈內第二行程式碼
迴圈內最後一行程式碼
迴圈外的程式碼
i = 0
while i < 5:
print(i)
i += 1
# 0
# 1
# 2
# 3
# 4
例1. 計算 1 至指定數字的平方和
end = 5
i = 1
square_sum = 0
while i <= end:
square_sum += i**2
i += 1
print(square_sum)
# 55
例2.
num = 1
summation = 0
while num < 20:
if num % 2 == 1:
summation += num
else:
summation -= num
num += 1
print(summation)
# 10
例3.計算字元出現的次數
string = '和尚端湯上塔,塔滑湯灑湯燙塔。和尚端塔上湯,湯滑塔灑塔燙湯。'
i = '湯'
num = 0
count = 0
while num < len(string):
if string[num] == i:
count += 1
num += 1
print('湯出現次數:' + str(count))
例4.使用 while 迴圈計算平均分
scores = [50, 60, 45, 85, 60, 77, 90,
44, 55, 15, 100, 25, 65, 44,
15, 20, 75, 90, 66, 45, 78,
44, 41, 80, 96, 84, 50, 51]
num = 0
total = 0
while num < len(scores):
total += scores[num]
num += 1
average = total / len(scores)
print('平均分數:', average)
# 平均分數: 58.92857142857143
例5.使用 for 迴圈計算平均分
scores = [50, 60, 45, 85, 60, 77, 90,
44, 55, 15, 100, 25, 65, 44,
15, 20, 75, 90, 66, 45, 78,
44, 41, 80, 96, 84, 50, 51]
num = 0
total = 0
while num < len(scores):
total += scores[num]
num += 1
average = total / len(scores)
print('平均分數:', average)
# 平均分數: 58.92857142857143
例6.讓使用者輸入數字值到猜中預設答案
ans = 55
num = int(input())
while num != ans:
if num > ans:
print('猜太高了')
else:
print('猜太低了')
num = int(input())
print('恭喜,猜中了')
| | for | while
------------- | --------------------------------
|使用時機 |可以知道迴圈數,處理資料為序列|未知迴圈數
|注意事項 |起始值、終點值、迴圈數 |判斷條件、變數更新