-3

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

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()
4

2 回答 2

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

这将启动您的代码。

于 2013-02-22T02:38:07.807 回答
0

Python has this functionality built in as the sum function.

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()
于 2013-02-22T02:35:25.470 回答