【问题标题】:Python Calculator encountering infinite loopsPython计算器遇到无限循环
【发布时间】:2015-10-02 09:30:19
【问题描述】:

我已经为此苦苦挣扎了几个小时,但我无法完全解决这个问题......所以当我运行它时,它会立即从while 块的异常部分。

我唯一能想到的是它进入了一个无限循环,因为它没有读取 main(),或者我的逻辑完全错误。为什么它会从一个似乎什么都不存在的结构中读取一个字符串......问题是“账单多少钱?”甚至从未出现(这应该是用户看到的第一件事).. 它只是直接进入循环。

我知道我错过了一些非常愚蠢的东西,但我似乎无法找到代码的行为方式。

# what each person pays, catch errors
def payments(bill,ppl):
    try:
        return round((bill/ppl),2)
    except: 
        print ('Invalid Calculation, try again')

#function to calculate tip, catch any errors dealing with percentages
def tip(bill,ppl,perc):
    try:
        return round(((bill * (perc/100))/ppl),2)   
    except: 
        print ('Please retry calculation with valid tip percentage')

'''
    function of body that will 
    ask each question and will catch errors(if any), 
    and continue to loop until valid entry is given
'''

def main():
    print ("How much is the bill?")
    while True:
        try: 
            total_bill = float(raw_input('>> $')) 
            break
        except:
            print("")
            print("Must be a number value")
            print("")
    print("")

    print ("How many people?")
    while True:
        try:
            num_ppl = int(raw_input('>>'))
            break
        except:
            print("")
            print("Must be a number value")
            print("")
        print("")

print ("Tip Percentage?")
while True:
    try:
        perc = int(raw_input('>> %'))
        break
    except:
        print("")
        print("Must be a number value")
        print("")   

print ("")
print ("Calculating Payment...")

    # Create variables to calculate total pay
bill_payment = payments(total_bill,num_ppl)
tip_payment = tip(total_bill,perc,num_ppl)
total_payment = float(bill_payment)+float(tip_payment)

    #print each variable out with totals for each variable
print ('Each Person pays $%s for the bill' % \
      str(bill_payment))
print ('Each Person pays $%s for the tip' % \
      str(tip_payment))
print ('Which means each person will pay a total of $%s' % \
      str(total_payment))


if __name__ == '__main__':
    main()

【问题讨论】:

  • 你是不是故意不缩进print ("Tip Percentage?")之后的行?
  • 请使用except ValueError: 而不仅仅是except:。您将获得有关这部分错误的更多信息(我怀疑由于某种原因引发了异常,而不是错误的浮点值)。特别是,到达输入流的末尾会产生这样一个无限循环。
  • 你确实需要修复你的缩进,目前它会报错不创建无限循环
  • 达到 EOF 将引发 exceptions.EOFError 例如
  • 我注意到 total_billnum_ppl 在此示例中从未定义。还要检查您如何定义def tip(bill,ppl,perc) 以及您如何称呼它略有不同。 tip(total_bill,perc,num_ppl)

标签: python loops main


【解决方案1】:
  1. 从第 44 行到第 68 行缺少缩进
  2. 如果您使用的是 python 3,则应将 raw_input() 替换为 input() (https://docs.python.org/3/whatsnew/3.0.html)

工作 Python 3 版本:

 # what each person pays, catch errors
def payments(bill,ppl):
    try:
        return round((bill/ppl),2)
    except: 
        print ('Invalid Calculation, try again')

#function to calculate tip, catch any errors dealing with percentages
def tip(bill,ppl,perc):
    try:
        return round(((bill * (perc/100))/ppl),2)   
    except: 
        print ('Please retry calculation with valid tip percentage')

'''
    function of body that will 
    ask each question and will catch errors(if any), 
    and continue to loop until valid entry is given
'''

def main():
    print ("How much is the bill?")
    while True:
        try: 
            total_bill = float(input('>> $')) 
            break
        except:
            print("")
            print("Must be a number value")
            print("")
    print("")

    print ("How many people?")
    while True:
        try:
            num_ppl = int(input('>>'))
            break
        except:
            print("")
            print("Must be a number value")
            print("")
        print("")

    print ("Tip Percentage?")
    while True:
        try:
            perc = int(input('>> %'))
            break
        except:
            print("")
            print("Must be a number value")
            print("")   

    print ("")
    print ("Calculating Payment...")

        # Create variables to calculate total pay
    bill_payment = payments(total_bill,num_ppl)
    tip_payment = tip(total_bill,perc,num_ppl)
    total_payment = float(bill_payment)+float(tip_payment)

        #print each variable out with totals for each variable
    print ('Each Person pays $%s for the bill' % \
          str(bill_payment))
    print ('Each Person pays $%s for the tip' % \
          str(tip_payment))
    print ('Which means each person will pay a total of $%s' % \
          str(total_payment))


if __name__ == '__main__':
    main()

【讨论】:

  • 谢谢,我需要更改 raw_input() --> input(),我认为这是合乎逻辑的东西,而不是句法,所以我的视野太狭隘了。我缩进了指定的行并清理了它。它现在完美运行。再次感谢。
【解决方案2】:

您似乎遇到了缩进问题,来自以下行:

print ("Tip Percentage?")

直到行:

if __name__ == '__main'__:

代码需要有更多的缩进,因此它将成为您的主要部分。

此外,最好捕获异常并打印其消息,以便您可以轻松找到导致异常的原因并修复它, 请更改:

except:
        print("")
        print("Must be a number value")
        print("") 

到这里:

except Exception, e:
        print("")
        print("Must be a number value (err: %s)" % e)
        print("") 

【讨论】:

    猜你喜欢
    • 2015-01-06
    • 2012-11-20
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 2013-09-06
    • 2011-07-12
    • 2018-09-22
    • 1970-01-01
    相关资源
    最近更新 更多