无限循环问题和添加raw_input结果

时间:2015-08-11 20:58:04

标签: python while-loop infinite-loop break raw-input

现在,我正在尝试循环过程中的一些练习。不幸的是,我碰到了一些问题,并希望你们所有人都可以帮助我。

问题:

编写一个包含以下输出的脚本:

Welcome to the receipt program!
Enter the value for the seat ['q' to quit]: five
I'm sorry, but 'five' isn't valid. Please try again.
Enter the value for the seat ['q' to quit]: 12
Enter the value for the seat ['q' to quit]: 15
Enter the value for the seat ['q' to quit]: 20
Enter the value for the seat ['q' to quit]: 30
Enter the value for the seat ['q' to quit]: 20
Enter the value for the seat ['q' to quit]: q

Total: $97

这是我的代码:

print "Welcome to the receipt program"
while True:
    value = raw_input('Enter the value for the seat [Press q to quit]: ')

    if value == 'q':
        break

    print 'total is {}'.format(value)
    while not value.isdigit():
        print "I'm sorry, but {} isn't valid.".format(value)
        value = raw_input("Enter the value for the seat ['q' to quit]: ")

我面临的问题:

  1. 当我运行代码时,我按了q。什么都没有出现。
  2. 如果值==' q'?
  3. ,如何添加值的总金额?

1 个答案:

答案 0 :(得分:2)

您正在循环中打印总计,而您最终想要完成此操作。此外,您想积累总额:

print "Welcome to the receipt program"

total = 0
while True:
    value = raw_input('Enter the value for the seat [Press q to quit]: ')

    if value == 'q':
        break

    if value.isdigit():
        total += int(value)
    else:
        print "I'm sorry, but {} isn't valid.".format(value)

print 'total is {}'.format(total)