sum = 0
avg = 0
cnt = 0
n = int(input("Enter a number (-1 to end):"))
while n!=-1:
cnt = cnt+1
sum = sum+n
n = int(input("Enter a number (-1 to end):"))
avg=sum/cnt
print('sum=',sum,'average=',avg)
total = 0
avg = 0
i = 0
score = input("請依序輸入成績(空格分開): ")
score_list = list(map(float, score.split(' '))) # 將成績轉成列表
Len = len(score_list) # 成績數量
while i < Len:
total += score_list[i] # 總分
avg = total / Len # 平均
print("總分={:.2f} 平均={:.2f}".format(total, avg)) # 取自小數點第2位
順便附上不用While用法:
total = 0
avg = 0
score = input("請依序輸入成績(空格分開): ")
score_list = list(map(float, score.split(' '))) # 將成績轉成列表
total = sum(score_list) # 總分
avg = total / len(score_list) # 平均
print("總分={:.2f} 平均={:.2f}".format(total, avg)) # 取自小數點第2位
times_count = 0
total = 0
while True:
n = int(input("請輸入分數,輸入'-1'結束填入 => "))
if n == -1:
break
else:
total += n
times_count += 1
print("總分 =>",float(total),"\t平均 =>",total/times_count)
float(total) 只是為了要符合你總分使用浮點數的需求,可選擇要不要轉型。
☑用while迴圈
☑四科分數加總
☑四科分數平均
do_your_homework_by_yourself = True
while do_your_homework_by_yourself:
my_scores = [78, 65, 91, 53]
my_sum = sum(my_scores)
my_avg = my_sum / len(my_scores)
print(
f"""分數:{my_scores[0]}
分數:{my_scores[1]}
分數:{my_scores[2]}
分數:{my_scores[3]}
總分={my_sum} 平均={my_avg}"""
)
do_your_homework_by_yourself = False