I am working on accessing a variable outside of a function. Here is part of my code:
def main():
trigger_gmm() = 0
log = []
def spatter_tracking_cb(ts, clusters):
global trigger_gmm
for cluster in clusters:
log.append([ts, cluster['id'], int(cluster['x']), int(cluster['y']), int(cluster['width']),
int(cluster['height'])])
if cluster['width'] >= 200:
trigger_gmm = 1
else:
trigger_gmm = 0
print(trigger_gmm)
while True:
print(trigger_gmm)
if trigger_gmm == 1:
print("print something")
if __name__ == "__main__":
main()
I get the output like this:
NameError: name 'trigger_gmm' is not defined
Any ideas would be much appreciated!
You have three issues in that code:
trigger_gmm() = 0 - You need to remove the parenthesis
You need to move the global variable definition up to the beginning of the main function
The if __name__ == "__main__": is not reached as it is after the while loop, you need to move it up.
EDIT:
I added a global declaration to the main module (above the main function) and inside the spatter_tracking_cb function. This is because you need to indicate that the variable trigger_gmm is a global variable whenever you use it.
This code seems to work for me:
global trigger_gmm
def main():
global trigger_gmm
trigger_gmm = 0
log = []
def spatter_tracking_cb(ts, clusters):
global trigger_gmm
for cluster in clusters:
log.append([ts, cluster['id'], int(cluster['x']), int(cluster['y']), int(cluster['width']),
int(cluster['height'])])
if cluster['width'] >= 200:
trigger_gmm = 1
else:
trigger_gmm = 0
print(trigger_gmm)
if __name__ == "__main__":
main()
while True:
print(trigger_gmm)
if trigger_gmm == 1:
print("print something")
trigger_gmm = 0
Remove parenthesis.
You also don't need global trigger_gmm as this variable will be available within scope of main function.
https://realpython.com/python-scope-legb-rule/#nested-functions-the-enclosing-scope
I am no Python user, but from it looks like you are calling variables that are not in a "global" scope.
Every variable defined in a function or loop, is not accessible by another function unless stated so.
Try defining your variable outside of the function, or make it global
As stated before.
W3Schools
This question already has answers here:
Using global variables in a function
(25 answers)
Closed 1 year ago.
Sorry for the beginner question. In the below code, the output I'm getting is "Original" and not "Function". Doesn't the value of name change after passing through the function? Thanks
global name
name = "Original"
def test():
name = "Function"
test()
print(name)
Use the global keyword in the function.
name = "Original" # define name
def test(): # define our function
global name # this function can now change name
name = "Function" # change the value
test() # run the function
print(name) # returns Function
I'd assume global needs to be in the function so you could do something like this, where a function can use text without effecting the text var:
text = "Original"
def test():
global text
text = "Function"
def printText(text):
textToPrint = text # use text var without any issues in this function
print(textToPrint)
test()
print(text)
global declarations go inside the function you want to apply them to, not at the top-level.
name = "Original"
def test():
global name
name = "Function"
test()
print(name)
name = "Original" #global variable
def test():
#to update the global value you have to declare it here
global name
name = "Function"
test()
print(name)
you can read more about it here, https://www.programiz.com/python-programming/global-keyword
I'm currently working on a town of salem-esc project for a class but I've ran into an issue. I have been trying to make it so that Suspect_ID is available globally but for some reason it is instead saying ("name 'Suspect_ID' is not defined", I'm tried making it outside of the statement with the rest of my global variables to no avail as well. Any suggestions would be helpful, and if any other information is needed feel free to ask, I hope you have better luck with this program than I am currently having.
def readinSuspects():
#local variables
global Suspect_name
Suspect_name=["","","","","","","","","",""]
global Suspect_age
Suspect_age=[0,0,0,0,0,0,0,0,0,0]
global Suspect_motive
Suspect_motive=["","","","","","","","","",""]
global Suspect_ID
Suspect_ID=[0,0,0,0,0,0,0,0,0,0]
global IsMurderer
IsMurderer=[False,False,False,False,False,False,False,False,False,False]
#subprogram body
file = open("suspects.txt","r")
for i in range(0,9):
Suspect_name[i],Suspect_age[i],Suspect_motive[i],
Suspect_ID[i]=file.readline().split(',')
return Suspect_name,Suspect_age,Suspect_motive,Suspect_ID,IsMurderer
edit: I'm now realising the issue may lie elsewhere so following is gonna be the program in it's entirety, it's far from finished and I am aware there are many other bugs etc.
import random
#Global variable
Guesses=[0]
Murderer=[0]
#Read In Function
def readinSuspects():
#local variables
global Suspect_name
Suspect_name=["","","","","","","","","",""]
global Suspect_age
Suspect_age=[0,0,0,0,0,0,0,0,0,0]
global Suspect_motive
Suspect_motive=["","","","","","","","","",""]
global Suspect_ID
Suspect_ID=[0,0,0,0,0,0,0,0,0,0]
global IsMurderer
IsMurderer=[False,False,False,False,False,False,False,False,False,False]
#subprogram body
file = open("suspects.txt","r")
for i in range(0,9):
Suspect_name[i],Suspect_age[i],Suspect_motive[i],
Suspect_ID[i]=file.readline().split(',')
return Suspect_name,Suspect_age,Suspect_motive,Suspect_ID,IsMurderer
#randomly assign murderer
readinSuspects(Suspect_ID)
Murderer = random.randint(0,9)
for i in range(0,9):
if Murderer == i:
#print Suspect_ID if working
print(Suspect_ID[i])
First of all your method readinSuspects() does not take parameters, but you invoke it with one argument - Suspect_ID which is not defined yet.
I have reworked your code so now it must work:
import random
#Global variable
Suspect_name = []
Suspect_age = []
Suspect_motive = []
Suspect_ID = []
IsMurderer = []
Guesses=[0]
Murderer=[0]
#Read In Function
def readinSuspects():
#local variables
global Suspect_name
Suspect_name=["","","","","","","","","",""]
global Suspect_age
Suspect_age=[0,0,0,0,0,0,0,0,0,0]
global Suspect_motive
Suspect_motive=["","","","","","","","","",""]
global Suspect_ID
Suspect_ID=[0,0,0,0,0,0,0,0,0,0]
global IsMurderer
IsMurderer=[False,False,False,False,False,False,False,False,False,False]
#subprogram body
file = open("suspects.txt","r")
for i in range(0,9):
Suspect_name[i],Suspect_age[i],Suspect_motive[i], Suspect_ID[i]=file.readline().split(',')
return Suspect_name,Suspect_age,Suspect_motive,Suspect_ID,IsMurderer
#randomly assign murderer
readinSuspects()
Murderer = random.randint(0,9)
for i in range(0,9):
if Murderer == i:
#print Suspect_ID if working
print(Suspect_ID[i])
Also read about if __name__ == '__main__': - it is a good python practice, but without it it still works. And here you can read how to define global vars in python How to define global variables in python SO
Your code has much more to be discussed, but I will leave your teacher to do it ;)
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()
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.
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