Python returns global variable not defined - python

I have a method that inside it I scan an excel file in python and in another method I want to check an entry in a list in which I extracted the data from the excel sheet in the first method as follows:
def first():
nodes_sh = xlrd.open_workbook(file_location)
sh_method = nodes_sh.sheet_by_index(0)
global node_data_inter
node_data_inter = [[sh_method.cell_value(rr, co) for co in range(sh_method.ncols)] for rr in range(sh_method.nrows)] #O(rows*cols) # A loop to get all the data in the excel sheet of "Nodes Co-ordinates"
global node_positions_ascending_inter
node_positions_ascending_inter = dc.deepcopy(node_data_inter) #O(rows*cols)
for rowss in range(len(node_positions_ascending_inter)): #O(rows)
del (node_positions_ascending_inter[rowss][0:3])
del (node_positions_ascending_inter[rowss][2])
def using_from_first_method():
global node_positions_ascending_inter
if node_positions_ascending_inter[0][0] == 1.25:
print "Yes"
An error message is outputted when I type using_from_first_method()
NameError: global name 'node_positions_ascending_inter' is not defined
Why is it outputted as I already have defined node_positions_ascending_inter to be a global variable?

You need to declare node_positions_ascending_inter as a global in the using_from_first_method function. I got the below code (simplification) to run just fine.
def first():
global node_positions_ascending_inter
node_positions_ascending_inter = [1.25, 1.5, 1.3, 1.45]
def using_from_first_method():
global node_positions_ascending_inter
if node_positions_ascending_inter[0] == 1.25:
print("Yes")
first()
using_from_first_method()
If you are still having issues maybe the problem lies in the filling of the array. Are you sure the first method is being called and successfully creating the global before the second tries to access it? Also, see the docs on globals here.

Related

How to access a variable outside of a function (access from a loop)?

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

assigning values to global variables in python [duplicate]

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

Python 3: Suspect_ID is not defined

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

Python Variable - name '' is not defined

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

keeping changed data global variables

I have a global variable that I change in a function but when I call the global variable later in code in a different function, it doesn't store the change when the variable is first called:
name = "noname"
def username():
print ("It would help if I had a name to go by, please enter a name.")
global name
name = input()
def character():
global name
print ("Character overview:\nName:"+name+"")
And the output of character() is noname instead of the input.
Is there a way keeping the change in the first function?
This works for me.
name = "noname"
def user():
global name
name = input()
def char():
# Works with or without global here
print(name)
user()
char()

Categories

Resources