Python 计算器遇到无限循环

Python Calculator encountering infinite loops

我已经为此苦苦挣扎了几个小时,我无法完全解决这个问题...所以当我 运行 它立即进入 [=18 的无限循环=] 来自 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?")

直到行:

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