确定用户输入的总和,产品和平均值

时间:2017-09-20 02:02:12

标签: python

我正在做一些需要我做以下工作的作业:

  

编写一个程序,该程序从用户接收一系列数字,并允许用户按下回车键以指示他或她已完成提供输入。用户按下回车键后,程序应打印数字的总和,数字的乘积和数字的平均值。

     

使用以下输入运行程序:
   1,2,3,4,5,6,7,8
   2,24,11,1,4,10
  输入无号码

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

从用户处取数,直到用户按“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()

3 个答案:

答案 0 :(得分:1)

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

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

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")

答案 1 :(得分:0)

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

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键。一旦输入键被击中,我得到所有值并打印出来。

答案 2 :(得分:0)

numbers = []
print("enter key to stop")
while(True):
    num = input("enter a number :")
    if num:
        numbers.append(int(num))
    elif(num == ''):
            break
sum_num =0
for num in numbers:
    sum_num += num
avg = sum_num / len(numbers)
print(sum_num)
print(avg)