1

刚开始使用一本较旧的 Python 书籍,学习循环并尝试创建一个循环来累积用户输入,然后显示总数。问题是这本书只展示了如何用一个范围来做到这一点,我想让用户输入任意数量的数字,然后显示总数,例如,如果用户输入 1、2、3、4,我会需要 python 输出 10,但我不想让 python 绑定到一系列数字。这是我有一个范围的代码,正如我上面所说,我需要在不被绑定到一个范围的情况下进行这个用户输入。我还需要为我想要制作的那种程序申请哨兵吗?

def main():

    total = 0.0

    print ' this is the accumulator test run '
    for counter in range(5):  #I want the user to be able to enter as many numbers
        number = input('enter a number: ') #as they want. 
        total  = total + number
    print ' the total is', total

main()
4

3 回答 3

0

使用相同的逻辑,只需用while循环替换它。当用户输入时循环退出0

def main():
    total = 0
    print 'this is the accumulator test run '
    while True:
        number = input('enter a number: ')
        if number == 0:
            break
        total += number
    print 'the total is', total

main()

只是为了好玩,这是一个单行解决方案:

total = sum(iter(lambda: input('Enter number (or 0 to finish): '), 0))

如果您希望它立即显示:

print sum(iter(lambda: input('Enter number (or 0 to finish): '), 0))
于 2013-10-17T14:32:13.997 回答
0

你需要一个while循环

def main():
    total = 0.0
    print ' this is the accumulator test run '
    # Loop continuously.
    while True:
        # Get the input using raw_input because you are on Python 2.7.
        number = raw_input('enter a number: ')
        # If the user typed in "done"...
        if number == 'done':
            # ...break the loop.
            break
        # Else, try to add the number to the total.
        try:
            # This is the same as total = total + float(number)
            total += float(number)
        # But if it can't (meaning input was not valid)...
        except ValueError:
            # ...continue the loop.
            # You can actually do anything in here.  I just chose to continue.
            continue
    print ' the total is', total
main()
于 2013-10-17T14:33:33.253 回答
0

使用 while-loop 循环不确定的次数:

total = 0.0
print 'this is the accumulator test run '
while True:
    try:
        # get a string, attempt to cast to float, and add to total
        total += float(raw_input('enter a number: '))
    except ValueError:
        # raw_input() could not be converted to float, so break out of loop
        break
print 'the total is', total

试运行:

this is the accumulator test run 
enter a number: 12
enter a number: 18.5
enter a number: 3.3333333333333
enter a number: 
the total is 33.8333333333
于 2013-10-17T14:34:32.943 回答