如何添加要存储在变量中的数字?

时间:2013-02-22 02:27:00

标签: python python-3.x

这是我必须解决的问题:编写一个程序来汇总用户输入的一系列数字。该程序应首先提示用户要求总和的数量。然后它应输入每个数字并打印总和。这就是我到目前为止所做的:

def excercise13():

print("Programming Excercise 13")
print("This program adds a series of numbers.")
while True:
    try:
        numberTimes = float(input("Enter how many numbers will be added: "))
    except ValueError:
        print("Invalid input.")
    else:
        break
numberTimes = int(numberTimes)
while True:
    try:
        for i in range(1,(numberTimes+1)):
            ("""I don't know what to put here""")
    except ValueError:
        print("Invalid input.")
    else:
        break
totalSum =
print("The sum of",nums,"is:",totalSum)
print()

excercise13()

2 个答案:

答案 0 :(得分:0)

Python将此功能内置为sum函数。

def makesum():    
    try:
        numbers = input('Enter the numbers to sum, comma seperated: ')
        print 'The sum is {0}'.format(sum(numbers))
    except:
        print 'Input invalid. Try again.'
        makesum()

makesum()

答案 1 :(得分:0)

我将根据您的代码,代码块的代码块来完成解决方案。

def excercise13():

    currentnumber = 0

在这里,我们创建函数excercise13()并将currentnumber设置为0

    print("Programming Excercise 13")
    print("This program adds a series of numbers.")
    while True:
        try:
            numberTimes = int(input("Enter how many numbers will be added: "))
        except ValueError:
            print("Invalid input.")
        else:
            break

你应该使用int而不是float.你能想象做一个过程3.5次吗?这也减少了您之前的重复次数。

    for x in range(numbertimes): #More pythonic way.
        new_number = input ("Please enter a number to be added.")
        currentnumber += new_number

以上代码块使程序要求新的numbertimes次。然后,它会将此数字添加到currentnumber

    totalSum = currentnumber
    print("The sum of",nums,"is:",totalSum)
    print()

这会将totalSum设置为最终currentnumber

excercise13()

这会启动您的代码。