Accessing a variable within a function from another function? python
Question:
How would it be possible to get the value of Accessme in the mainloop function?
def example():
test=True
while test:
print("some stuff")
if test2==True:
Accessme = 400 # Need to access this
print("some stuff")
if test3==True:
print("some stuff")
mainloop(x,y)
elif test2==False:
print("some stuff")
def mainloop(x,y):
cheese = 1
noise = []
for something in somecodehere:
print("some stuff")
output = some more code here
print("some stuff",Accessme ) #Calling from here
This is the error i get:
> NameError: name 'Accessme' is not defined
Answers:
If you want access to Accessme
to be global (that is, outside of any particular function), then you need to tell each function that this is the case:
global Accessme
Use of globals is usually in bad style. If you want to get information out of a function, it would be better return that information, just as getting information into a function is best done by a parameter.
Your example code was messy to word with so I simplified enough so you understand the concept:
def example():
test=True
while test:
Accessme = 400 #Assign the variable
break
return Accessme #This will return the variable. Accessme is local to the function example and nowhere else.
def mainloop(x=0,y=0):
cheese = 1
noise = []
print("some stuff",example() ) #You can grab the output from example by calling the function example, not Accessme.
mainloop()
I advise you read up on Scope. Your issue was Accessme is not in the scope of mainloop.
How would it be possible to get the value of Accessme in the mainloop function?
def example():
test=True
while test:
print("some stuff")
if test2==True:
Accessme = 400 # Need to access this
print("some stuff")
if test3==True:
print("some stuff")
mainloop(x,y)
elif test2==False:
print("some stuff")
def mainloop(x,y):
cheese = 1
noise = []
for something in somecodehere:
print("some stuff")
output = some more code here
print("some stuff",Accessme ) #Calling from here
This is the error i get:
> NameError: name 'Accessme' is not defined
If you want access to Accessme
to be global (that is, outside of any particular function), then you need to tell each function that this is the case:
global Accessme
Use of globals is usually in bad style. If you want to get information out of a function, it would be better return that information, just as getting information into a function is best done by a parameter.
Your example code was messy to word with so I simplified enough so you understand the concept:
def example():
test=True
while test:
Accessme = 400 #Assign the variable
break
return Accessme #This will return the variable. Accessme is local to the function example and nowhere else.
def mainloop(x=0,y=0):
cheese = 1
noise = []
print("some stuff",example() ) #You can grab the output from example by calling the function example, not Accessme.
mainloop()
I advise you read up on Scope. Your issue was Accessme is not in the scope of mainloop.