代码之家  ›  专栏  ›  技术社区  ›  WiTcHer_Pro

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

  •  0
  • WiTcHer_Pro  · 技术社区  · 9 年前

    现在,我正在尝试循环过程中的一些练习。不幸的是,我遇到了一些问题,希望你们都能帮助我。

    问题是:

    编写具有以下输出的脚本:

    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. 如果value==“q”,我如何添加值的总量?
    1 回复  |  直到 9 年前
        1
  •  2
  •   Maksim Solovjov    9 年前

    你正在循环中打印你的总数,而你想在最后打印。此外,您还希望累积您的总数:

    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)