[英]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.