未定义Python变量名“”

2024-09-28 22:21:22 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我是Python的新手。在

变量的声明是令人沮丧的,因为它应该是容易的,但我有如此困难的时间使这项工作。。 我读过其他的stackoverflow问题,显然Python中没有初始化,我需要关键字:global before variable在不同的地方使用它。。在

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

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

选项1。在

^{pr2}$

选项2。在

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

都不管用。。 当我在下面进行这样的计算时,我得到一个错误:NameError:name'newweightferseconditem'没有定义。在

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

Tags: nameappconvertgetifdef选项float
2条回答

如果要将newWeightForSecondItem作为全局变量,可以尝试以下操作:

 newWeightForSecondItem = None

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

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

我花了很多时间来弄清楚我为什么会犯这个错误。 NameError:未定义名称“newWeightForSecondItem”。在

然而,这并不是主要问题。我忘了将newweightForSecondem的字符串转换为float数据类型。在我将其更改为float(newweightferseconditem)之后,它就可以工作了。这是一个很容易出错的错误,我认为python的错误并不是很有帮助。在

谢谢大家的评论。在

相关问题 更多 >