我正在学习 Python,并尝试编写一个小费计算器作为第一个小项目。
我想出了以下代码:
meal = raw_input("Cost of meal: ")
tax = raw_input("Tax: ")
tip = raw_input("Tip: ")
def tipCalc(meal, tax, tip):
def convertInput(meal, tax, tip):
try:
retMeal = int(meal)
retTax = int(tax)
retTip = int(tip)
except ValueError:
retMeal = float(meal)
retTax = float(tax)
retTip = float(tip)
return retMeal
return retTax
return retTip
convertInput(meal, tax, tip)
retTax = retTax / 100
retTip = retTip / 100
total = retMeal + retTax + retTip
print total
tipCalc(meal, tax, tip)
但是,我收到以下错误:
Traceback (most recent call last):
File "/Users/dustin/Desktop/tipcalc.py", line 27, in <module>
tipCalc(meal, tax, tip)
File "/Users/dustin/Desktop/tipcalc.py", line 22, in tipCalc
retTax = retTax / 100
UnboundLocalError: local variable 'retTax' referenced before assignment
这似乎是一个需要修复的简单错误,但我似乎无法在我的逻辑中找到错误。
请您参考如下方法:
你可能是这个意思:
def tipCalc(meal, tax, tip):
def convertInput(meal, tax, tip):
try:
retMeal = int(meal)
retTax = int(tax)
retTip = int(tip)
except ValueError:
retMeal = float(meal)
retTax = float(tax)
retTip = float(tip)
return retMeal, retTax, retTip
retMeal, retTax, retTip = convertInput(meal, tax, tip)
retTax = retTax / 100
retTip = retTip / 100
total = retMeal + retTax + retTip
print total
tipCalc(meal, tax, tip)
如果你想从一个类方法中返回多个值,多个返回语句是行不通的。您需要有 1 个返回语句,并根据需要发送回尽可能多的值。
此外,错误是在计算 retTax = retTax/100 时,变量尚未声明。
