我正在做一些功课,要求我做以下事情:

Write a program that receives a series of numbers from the user and allows the user to press the enter key to indicate that he or she is finished providing input. After the user presses the enter key, the program should print the sum of the numbers, the product of the numbers, and the average of the numbers.
Run your program with the following inputs:
1, 2, 3, 4, 5, 6, 7, 8
2, 24, 11, 1, 4, 10
Enter no number

这是我到目前为止所拥有的,但我的数字并没有正确显示出来。 有人能告诉我我做错了什么。 我是初学者,所以,如果你能用最简单的术语说话,那就太好了。

从用户那里取数字直到用户按下"Enter"

计算输入数字的总和,乘积和平均值

显示结果

#main program start
def main():
#initialize variables
count = 0
sum = 0.0
product = 1.0
data = input("Enter a number or press Enter to quit:")
while True:
#request input from user
data = input("Enter a number or press Enter to quit:")
#set up the termination condition
if data =="":
break
#convert inputs into floats
number = float(data)
#calculate sum, product, and average
sum += number
product *= number
average = sum / number
#display results
print("The sum is", sum)
print("The product is", product)
print("The average is", average)
#main program end
main()

你不能得到平均值,直到你拥有所有数字....但总和和产品应该是正确的

此外,您将sum除以number。 您应该计算数字并除以计数。

不确定你的意思是价值是错误的。 除了平均水平之外,似乎没什么。

如果您想要平均值,则需要一个列表来收集值。 尝试手写你的算法,你会明白我的意思。

data = input("Enter a number or press Enter to quit:")
numbers = []
while True:
#request input from user
data = input("Enter a number or press Enter to quit:")
#set up the termination condition
if data =="":
break
#convert inputs into floats
numbers.append(float(data))
# these can all be done outside and after the while loop
count = len(numbers)
if count > 0:
_sum = sum(numbers)
product = 1.0
for n in numbers:
product *= n
average = _sum / float(count)
#display results
print("The sum is", _sum)
print("The product is", product)
print("The average is", average)
else:
print("Nothing was entered")

我建议在推送到数字列表之前检查输入是有效的float还是int类型。

我想到了,但那是OP的决定

当然,你说对了!

您不能使用sum作为变量名称。 注意我使用了_sum,它位于循环之下,而不是它之上

当我用计算器检查总和,产品和平均值时,数字与程序返回的数字相差不多。 此外,当我输入没有数字时,我收到一条错误消息。 我该如何解决?

在while循环退出后你应该print(numbers)

由于您一次输入一个数字,因此您没有所有数字。 最好让用户输入如下列表:

def main():
average = 0
sum_nums = 0
product = 1
nums = []
while True:
data = input("Enter a number or press Enter to quit:")
if data ==""
sum_nums = sum(nums)
for num in nums:
num *= product
average = sum_nums/len(nums)
print("The sum is {},".format(sum_nums))
print("The product is {}.".format(product))
print("The average is {}.".format(average))
else:
nums.append(data)
continue

它的工作原理是将所有输入输入到列表中。 退出输入的唯一方法是使用enter,如果输入为空,则它只能是Enter键。 一旦输入键被击中,我得到了所有的值并打印出来。

我不认为该任务要求为每个输入的值更新总和,平均值,产品

仅在按下回车键时才会更新这些值。 它位于if data ==""之下,因为它检查是否按下了回车键。