如何使用循环将数字添加到一起?

时间:2014-03-24 01:22:22

标签: python loops while-loop python-2.x

def adding():
    total = 0
    x = 0
    while x != 'done':
        x = int(raw_input('Number to be added: '))
        total = x + total
        if x == 'done':
            break
    print total

我无法弄清楚如何添加用户输入的数字,然后在输入完成后停止并打印总数'

2 个答案:

答案 0 :(得分:1)

当用户输入ValueError时,我假设用"done"对你大喊大叫?那是因为你在检查它是一个数字还是一个哨兵之前试图把它作为int。试试这个:

def unknownAmount():
    total = 0
    while True:
        try:
            total += int(raw_input("Number to be added: "))
        except ValueError:
            return total

或者,您可以通过执行以下操作来更改自己的代码:

def unknownAmount():
    total = 0
    x = 0
    while x != "done":
        x = raw_input("Number to be added: ")
        if x == "done":
            continue
        else:
            total += int(x)
    return total

但请注意,如果用户输入"foobar",它仍然会抛出ValueError而不会返回您的总数。

编辑:从评论中解决您的额外要求:

def unknownAmount():
    total = 0
    while True:
        in_ = raw_input("Number to be added: ")
        if in_ == "done":
            return total
        else:
            try:
                total += int(in_)
            except ValueError:
                print "{} is not a valid number".format(in_)

这样,如果转换为"done"失败,您将检查唯一有效的条目,该条目不是第​​一个数字(int),然后在用户处喊叫。

答案 1 :(得分:0)

这里有很多类似的问题,但到底是什么。最简单的是:

def adding():
    total = 0
    while True:
        answer = raw_input("Enter an integer: ")
        try:
            total += int(answer)
        except ValueError:
            if answer.strip() == 'done':
                break
            print "This is not an integer, try again."
            continue
    return total

summed = adding()
print summed

更奇特的问题是:

def numbers_from_input():
    while True:
        answer = raw_input("Enter an integer (nothing to stop): ")
        try:
            yield int(answer)
        except ValueError:
            if not answer.strip(): # if empty string entered
                break
            print "This is not an integer, try again."
            continue

print sum(numbers_from_input())

但是这里有一些python功能,如果你是begginer,你可能不知道

相关问题