Python-如何计算“ while”或“ for循环”的输入总数?

时间:2019-02-15 14:51:51

标签: python

使用for / while循环获取用户输入以计算总显示量,如下所示:

    Welcome to the receipt program:      
    Enter the value for the seat ['q' to quit]: 12   
    Enter the value for the seat ['q' to quit]: 15.50
    Enter the value for the seat ['q' to quit]: 9.98   
    Enter the value for the seat ['q' to quit]: 14.05    
    Enter the value for the seat ['q' to quit]: q               
    Total:$51.53    
    Enter the value for the seat ['q' to quit]: five   
    I'm sorry, but 'five' isn't valid. Please try again.

我能够打印输入并使用'q'中断循环,但无法计算总数


print "Welcome to receipt program!"

while true:
    receipt= raw_input('Enter the value for the seat [q to quit]:')
    if receipt == 'q':
        break
    if not receipt.isdigit():
        print "I'm sorry, but {}".format(receipt) + " isn't valid. Please try again"
    total = receipt
    print "total:{}".format(receipt)

1 个答案:

答案 0 :(得分:0)

print "Welcome to receipt program!"

total = 0
while true:
    receipt= raw_input('Enter the value for the seat [q to quit]:')
    if receipt == 'q':
        break
    if not receipt.isdigit():
        print "I'm sorry, but {}".format(receipt) + " isn't valid. Please try again"
    else:
        total += float(receipt)

print "total:%f" % receipt