2017-03-24 76 views
1

您好,我是Python的新手。Python变量 - 名称''未定义

变量声明令人沮丧,因为它应该很容易,但我有这样的困难时间,使这项工作.. 我读过其他stackoverflow的问题,显然没有这样的事情,在Python中的初始化,我需要关键字:全球变量之前使用它在不同的地方..

@app.route('/calculate', methods = ['GET'])  

def calculate(): 
     # get value from html by request.args.get() 

Option1。

global newWeightForSecondItem 
    if weightT1 != weightT2: 
     newWeightForSecondItem = convert(weightT1, weightT2, weight2) 

选项2

if weightT1 != weightT2: 
     global newWeightForSecondItem = convert(weightT1, weightT2, weight2) 

无论是工程.. 当我做这样的计算之下,我得到一个错误:NameError:名字 'newWeightForSecondItem' 没有定义。

if discountT2 == "percentage": 
     finalPrice2 = float((float(price2) - (float(price2) * float(discount2)))/newWeightForSecondItem) 
    elif discountT2 == "dollar": 
     finalPrice2 = float((float(price2) - float(discount2))/newWeightForSecondItem) 


def convert(weightT1, weightT2, weight2): 
    # converting calculation here 

return weight2 


# main method 
if __name__ == '__main__': 
    app.debug = True 
    app.run() 
+2

在Python中没有变量声明,所以这可能解释了为什么你发现它很困难。 –

+2

你可以发布一组更完整的代码......这是一个范围界定问题,你没有向我们展示你的范围。 – TemporalWolf

+0

@TemporalWolf基于您的建议,我添加了整体代码。谢谢。 –

回答

0

,如果你想拥有newWeightForSecondItem作为一个全局变量也许你可以试试这个:

newWeightForSecondItem = None 

@app.route('/calculate', methods = ['GET'])  
def calculate(): 
    global newWeightForSecondItem 
    if weightT1 != weightT2: 
     newWeightForSecondItem = convert(weightT1, weightT2, weight2) 

您声明/初始化全局变量,然后你可以使用它在函数内部

+0

感谢您的评论。我不再有同样的错误了,但现在我在计算中得到NonType .. –

+0

而不是newWeightForSecondItem =无,你应该在使用它之前初始化值。可能将它设置为newWeightForSecondItem = 0. –

+1

@GabrielFalcones将产生一个'ZeroDivisionError',因为他在分配给它之前调用它。 – TemporalWolf

1

我花了很多时间来弄清为什么我得到这个错误。 NameError:名称'newWeightForSecondItem'未定义。

但是,这不是主要问题。我忘了将字符串转换为newWeightForSecondItem的浮点数据类型。在我将其更改为浮动(newWeightForSecondItem)后,它可以工作。这是一个非常容易的错误,我认为python的错误不是很有帮助。

谢谢大家的所有意见。