[英]Calculating Average of 7 Numbers in Python
x = int(input())
Count = 0
Sum = 0
Average = 0
for i in range(7):
Sum = Sum + x
Count = Count + 1
else:
Average= Sum/Count
print("The sum is",Sum)
print("The average is",Average)
Trying to calculate average with this code of 7 numbers but unable to reach the last few lines.尝试使用此 7 个数字的代码计算平均值,但无法到达最后几行。 Any help would be gladly appreciated!任何帮助将不胜感激!
Assuming you want to ask the user for 7 different inputs (rather than calculating the average of the same number 7 times), give this a try, using list comprehension and the built-in functions sum
and len
to compute the mean:假设您要向用户询问 7 个不同的输入(而不是计算相同数字的平均值 7 次),请尝试一下,使用列表理解和内置函数sum
和len
来计算平均值:
num_values = 7
values_list = [int(input("Enter a number: ")) for _ in range(num_values)]
average = sum(values_list) / len(values_list)
print("The average is {}".format(average))
Alternatively, if you do want to calculate the average of the same number X times:或者,如果您确实想计算 X 次相同数字的平均值:
value = int(input("Enter a number: "))
print("The average is {}".format(value))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.