[英]how to get the average using for loop in python
在本練習中,您將創建一個程序來#計算用戶輸入的一組值的平均值。 用戶將輸入 0 作為#sentinel 值,以指示不再提供其他值#will。 如果用戶輸入的第一個值#by 是 0,您的程序應該顯示#appropriate 錯誤消息。
print("You first number should not be equal to 0.")
total=0
average_of_num=0
i=0
num=input("Enter a number:")
for i in num:
total=total+num
i=i+1
num=input("Enter a number(0 to quit):")
if i==0:
print("A friendly reminder, the first number should not be equal to zero")
else:
average_of_num=total/i
print("Counter",i)
print("The total is: ", total)
print("The average is: ",average_of_num)
看看這是否適合你。
entry_list = []
while True:
user_entry = int(input("Enter a non Zero number(0 to quit entering: "))
if user_entry == 0:
break
entry_list.append(user_entry)
total = 0
for i in entry_list:
total = total + i
avg = total/len(entry_list)
print("Counter",len(entry_list))
print("The total is: ", total)
print("The average is: ",avg)
如果只應該使用 for 循環試試這個..
num=[int(input("Enter a number:"))]
total=0
for i in num:
if i == 0:
break
total=total+i
x = int(input("Enter a number(0 to quit):"))
if x != 0:
num.append(x)
avg = total/len(num)
print("Counter: ",len(num))
print("The total is: ", total)
print("The average is: ",avg)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.