Reputation: 809
Hello I am a newbie to Python.
Declaration of variables is frustrating as it should be easy but I have such hard time to make this work.. I've read other stackoverflow questions and apparently there is no such thing as initialization in Python and I need keyword: global before variable to use it in different places..
@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)
Option 2.
if weightT1 != weightT2:
global newWeightForSecondItem = convert(weightT1, weightT2, weight2)
Neither works.. When I do such calculation below, I get an error: NameError: name 'newWeightForSecondItem' is not defined.
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()
Upvotes: 1
Views: 5109
Reputation: 809
I spent a lot time to figure out why I got this error. NameError: name 'newWeightForSecondItem' is not defined.
However, that was not the main issue. I forgot to convert string to float datatype for newWeightForSecondItem. After I changed it to float(newWeightForSecondItem), it works. This was a very easy mistake and I think python's error was not very helpful.
Thank you for all the comments, everyone.
Upvotes: 1
Reputation: 23
if you want to have newWeightForSecondItem as a global variable perhaps you can try this:
newWeightForSecondItem = None
@app.route('/calculate', methods = ['GET'])
def calculate():
global newWeightForSecondItem
if weightT1 != weightT2:
newWeightForSecondItem = convert(weightT1, weightT2, weight2)
You declare/initialize the global variable, and then you can use it inside the function
Upvotes: 0