Python 2.7.5,使用无限的用户输入进行循环,累积总数,应用sentinel?

时间:2013-10-17 14:27:14

标签: python python-2.7

刚开始使用旧的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()

3 个答案:

答案 0 :(得分: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))

答案 1 :(得分:0)

您需要while-loop

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

答案 2 :(得分:0)

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

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