简体   繁体   English

分配前引用的变量

[英]Variable Referenced Before Assignment

I am learning Python, and trying to write a tip calculator as a first small project. 我正在学习Python,并尝试编写一个提示计算器作为第一个小项目。

I came up with the following code: 我想出了以下代码:

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)

However, I am getting the following error: 但是,我收到以下错误:

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

This seems like a simple error to fix, but I can't seem to find an error in my logic. 这似乎是一个简单的错误,但我似乎找不到逻辑上的错误。

You probably mean this: 您可能是这个意思:

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)

If you wish to return multiple values from a class method, multiple return statements do not work. 如果希望从一个类方法返回多个值,则多个return语句不起作用。 You need to have 1 return statements, and send back as many values as you wish to. 您需要有1个return语句,并发送回任意数量的值。

Also, the error was, at the time of calculating retTax = retTax / 100 , the variable was not already declared. 同样,错误是在计算retTax = retTax / 100 ,尚未声明变量。

The other answers have covered the reason for the exception you're getting, so I'm going to skip over that. 其他答案涵盖了您遇到异常的原因,因此我将跳过该原因。 Instead, I want to point out a subtle mistake that's going to bite you sooner or later and make your code calculate the wrong values if either the tax or the tip are ever entered as whole numbers. 相反,我想指出一个微妙的错误,迟早会咬你,如果将税或小费输入为整数,会使代码计算错误的值。

IMPORTANT : This answer is true for Python 2.x (which I see you're using). 重要提示 :这个答案对于Python 2.x是正确的(我看到您正在使用)。 In Python 3.x, the default behavior of division changes and this answer would no longer be true (and your code would work correctly). 在Python 3.x中,除法的默认行为会更改,并且此答案将不再成立(并且您的代码将正常运行)。

With that in mind, let's look at something in the Python interpreter for a minute. 考虑到这一点,让我们看一下Python解释器中的内容。

Python 2.7.4 (default, Apr 19 2013, 18:28:01) 
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 2.0 / 3.0
0.6666666666666666
>>> 2 / 3
0

In the first example, we see what happens when we divide two floats together: we get a float with the best approximation of the result we can. 在第一个示例中,我们看到将两个浮点数相除会发生什么:我们得到的浮点数与结果可以得到的最佳近似。 (2/3 will never be exactly represented by a float, but it's a close enough result for nearly all purposes). (2/3永远不会由浮点数精确表示,但是对于几乎所有目的而言,它都是足够接近的结果)。 But see the second example? 但是看第二个例子吗? Instead of 0.666..., it returned 0. Why is that? 而不是0.666 ...,它返回0。为什么呢?

That's because in Python 2.x, dividing two int s together is guaranteed to always return an int , so it rounds down (always down) to the int. 这是因为在Python 2.x中,保证将两个int划分在一起总是会返回一个int ,因此它会四舍五入(始终向下)到int。 In combination with the % operator (which returns remainders), this lets you do "grade school" division, where 3 goes into 7 just 2 times, with 1 left over. %运算符(返回余数)结合使用,您可以进行“年级”除法,其中3乘2乘以7,剩下的1。 This is quite useful in many algorithms, so it's kept around. 这在许多算法中非常有用,因此一直保持下去。 If you want to use floating-point division (where you get a float result), you need to make sure that at least one of your numbers in the division is a float . 如果要使用浮点除法(得到float结果),则需要确保除法中至少有一个数字是float

Thus, you should do 2.0 / 3 or 2 / 3.0 if you want the 0.6666... result in our example. 因此,如果您想获得0.6666...结果,则应执行2.0 / 32 / 3.0 And in your code, you should either do: 在您的代码中,您应该执行以下任一操作:

retTax = retTax / 100
retTip = retTip / 100

or else you should change your convertInput() function to always return floats no matter what. 否则, convertInput()您都应该将convertInput()函数更改为始终返回浮点数。 I suggest the latter: 我建议后者:

def convertInput(meal, tax, tip):
    retMeal = float(meal)
    retTax = float(tax)
    retTip = float(tip)
    return retMeal, retTax, retTip

That way when you divide them by 100 later, you'll get a fraction. 这样,当您以后将它们除以100时,会得到分数。 Otherwise, you could have ended up with an int result in tax or tip, and gotten a rounded-off value in your calculation. 否则,您可能最终会得到int结果的税款或小费,并在计算中获得了四舍五入的值。

There's another way to change Python's behavior regarding division, with the from __future__ import division statement in Python 2.x (which applies some of the Python 3.x rules). 还有另一种方法可以更改Python关于除法的行为,使用Python 2.x中的from __future__ import division语句(适用于某些Python 3.x规则)。 I won't go into it in detail now, but now you know what to Google if you want to read more about it. 我现在不会详细介绍,但是现在您想了解更多有关Google的知识。

retMealretTaxretTip变量是本地convertInput和你不使用该函数的返回值,添加assignement:

retMeal, retTax, retTip = convertInput(meal, tax, tip)

Other than what the others have pointed out, I really see no real need for the function 除了别人指出的以外,我真的没有真正需要的功能

def convertInput(meal, tax, tip):

Just use floats from the beginning 从一开始就使用浮点数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM