如何使用循环加数?

0 投票
2 回答
1319 浏览
提问于 2025-04-17 23:35
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

这里有很多类似的问题,不过没关系。最简单的解决办法是:

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特性。

1

我猜你是说当用户输入 "done" 时,程序会给你报 ValueError 的错误吧?这是因为你在检查输入是否是数字或者特定的结束信号之前,就试图把它转换成 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 失败,再提醒用户。

撰写回答