Why does assigning to my global variables not work in Python?
Global variables are special. If you try to assign to a variable a = value
inside of a function, it creates a new local variable inside the function, even if there is a global variable with the same name. To instead access the global variable, add a global
statement inside the function:
a = 7
def setA(value):
global a # declare a to be a global
a = value # this sets the global value of a
See also Naming and binding for a detailed explanation of Python's naming and binding rules.
Python Global Variables - Not Defined?
You have to use global df
inside the function that needs to modify the global variable. Otherwise (if writing to it), you are creating a local scoped variable of the same name inside the function and your changes won't be reflected in the global one.
p = "bla"
def func():
print("print from func:", p) # works, readonly access, prints global one
def func1():
try:
print("print from func:", p) # error, python does not know you mean the global one
p = 22 # because function overrides global with local name
except UnboundLocalError as unb:
print(unb)
def func2():
global p
p = "blubb" # modifies the global p
print(p)
func()
func1()
print(p)
func2()
print(p)
Output:
bla # global
print from func: bla # readonly global
local variable 'p' referenced before assignment # same named local var confusion
bla # global
blubb # changed global
Python unable to access global variable in simple grade program
In the getInput
function, you declare that marks
will be a global variable, but never actually assign it. Since the scope of the global
keyword is only within that function, you actually never created a global variable marks
.
Then in getGrades
, you create another variable marks
, which is local to getGrades
, because you didn't declare marks
as global in getGrades
. This is why showGrades
cannot find the variable marks
; it is local to getGrades
.
Try making declaring marks
as a global inside of getGrades
, and I'm pretty sure the problem will be fixed.
For more see: What are the rules for local and global variables in Python?
Edit: To confirm my thinking I decided to do an experiment: I created a function where I declared, but never assigned a global variable. We then run the function, and use the built in globals
function to check if myglobalvariable
actually exists in the global scope
>>> def globaltest():
global myglobalvariable
>>> globaltest()
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'globaltest': <function globaltest at 0x0000027E24B11EA0>}
We see from the output above that, as expected, myglobalvariable
is not in the global scope.
Why is my global variable not working? (Python)
This is a working example but isnt it better that you pass name to prologue function instead of using global variable? It is another subject but you have to avoid using global.
import time
name = 0 #this part is at the top of the page, not actually just above the segment
def naming():
global name
print("A long, long time ago, there was a person who was born very ordinary, but would live to become very extraordinary.\n")
time.sleep(2)
while True:
name=input("Who are you? Give me your name.\n")
choice = input(f'You said your name was {name}, correct?\n')
if choice == "Yes":
prologue()
else:
return
def prologue():
global name
print(f'Very well, {name}. You were born with a strange gift that nobody could comprehend, at the time. You were born with the Favor of the Gods.')
if __name__ == '__main__':
naming()
Global variable not recognized in functions
In your case the variable you want to access is not global, it is in the scope of the class.
global_var = "global"
class Example:
class_var = "class"
def __init__(self):
self.instance_var = "instance"
def check(self):
print(instance_var) # error
print(self.instance_var) # works
print(class_var) # error
print(self.class_var) # works, lookup goes "up" to the class
print(global_var) # works
print(self.global_var) # works not
You only need the global
keyword if you want to write to a global variable. Hint: Don't do that because global variables that are written to bring nothing but pain and despair. Only use global variables as (config) constants.
global_var = "global"
class Example:
def ex1(self):
global_var = "local" # creates a new local variable named "global_var"
def ex2(self):
global global_var
global_var = "local" # changes the global variable
Example().ex1()
print(global_var) # will still be "global"
Example().ex2()
print(global_var) # willnow be "local"
Why are global variables accessible in some functions but not others?
This line is the difference:
index += 1
If you set/change a variable anywhere in the function, Python assumes it's a local rather than a global, everywhere in the function. That's the difference between your two functions, b()
doesn't try to change it.
To fix this, you can just out:
global index
at the top of your c()
function, which tells it to assume global no matter what. You may want to do that in b()
as well, just to be explicit and consistent.
Or, you could find a way to do this without globals, which is probably preferable :-) Something like:
index = 0
a = [1, 2, 3, 4]
def b(idx, arr):
print(idx)
print(arr)
def c(idx, arr):
print(idx)
print(arr)
while arr[idx] < 3:
idx += 1
return idx
b(index, a)
index = c(index, a)
Global variable doesn't work outside the function
You need to either declare the variable in global scope first
eg:
title = None
def get_history_events(requests, BeautifulSoup):
global title, facts
title = facts = None
url = 'https://cs.wikipedia.org/wiki/Hlavn%C3%AD_strana'
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0'}
r = requests.get(url, headers=header).text
soup = BeautifulSoup(r, 'lxml')
table = soup.find('div', class_ = 'mainpage-block calendar-container')
title = table.find('div', class_ = 'mainpage-headline').text
facts = table.find('ul').text
print(title)
or execute your funtion before calling print on it:
eg.:
def get_history_events(requests, BeautifulSoup):
global title, facts
title = facts = None
url = 'https://cs.wikipedia.org/wiki/Hlavn%C3%AD_strana'
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0'}
r = requests.get(url, headers=header).text
soup = BeautifulSoup(r, 'lxml')
table = soup.find('div', class_ = 'mainpage-block calendar-container')
title = table.find('div', class_ = 'mainpage-headline').text
facts = table.find('ul').text
get_history_events(<imagine your args here>)
print(title)
Related Topics
List on Python Appending Always the Same Value
Cartesian Product of Two Lists in Python
Execute Multiple Commands in Paramiko So That Commands Are Affected by Their Predecessors
Making the Background Move Sideways in Pygame
Using Django Time/Date Widgets in Custom Form
Applying Function with Multiple Arguments to Create a New Pandas Column
Multiple Modeladmins/Views for Same Model in Django Admin
How to Make a Scatter Plot Colored by Density in Matplotlib
What Are the Differences Between JSON and Simplejson Python Modules
Pandas: Merge (Join) Two Data Frames on Multiple Columns
Python Unicodedecodeerror - am I Misunderstanding Encode
Converting Xml to JSON Using Python
Python Multiprocessing Safely Writing to a File