Why is a global variable not changed in Python?
Can you give an example of where it isn’t ?
I think though, I can suggest what might be the issue :
- >>> a = 17
- >>> def func()
- >>> a = 23
- >>> print(2,a)
- >>> print(1,a)
- >>> func()
- >>> print(3,a)
- 1, 17
- 2, 23
- 3, 17
You might think that line 3 should overwrite the global variable in line 1, but Python simply doesn’t work like that.
Unless you tell Python otherwise the ‘a’ defined on line 3 is a local variable which is only used in the ‘func’ function. Python ignores the name overlap.
If you really want to use global values (not really a good idea - but there you go), you have to tell Python that ‘a’ inside ‘func’ is a global - and not a local.
- >>> a = 17
- >>> def func()
- >>> global a
- >>> a = 23
- >>> print(2,a)
- >>> print(1,a)
- >>> func()
- >>> print(3,a)
- 1, 17
- 2, 23
- 3, 23
As I suggested though, the use of global variables within a program is not really recommended - it is a bad habit to get into as it makes testing significantly more difficult.
If you insist on global variables - a better way is to make use of arguments and return values - that makes the functionality of ‘func’ only dependent on it’s inputs - makes testing so much easier.
- >>> a = 17
- >>> def func( value )
- >>> value = value +1
- >>> print(2,value)
- >>> return value
- >>> print(1,a)
- >>> a = func(a)
- >>> print(3,a)
- 1, 17
- 2, 18
- 3, 18
Another reason why you might have difficulty with global variables, if you are coming from the world of C, is that global variables are ONLY defined within a module; you have to use a dot notation to make use of a variable from one module in another - or import the variables with an alias :
- # module2.py
- value = 17
- # module1.py
- import module2
- print( module2.value ) # you cannot simply use 'value' here.
- # module3.py
- from module2 import value as value
- # module2.value now can be called value
- print( value )
You can now run either module1 or module3 and get the value of 17 as output.
Articoli simili
- Why am I not able to make a super chat on YouTube? Why does it say this feature isn’t available yet in your region?
- Is there any way in c to change the value of a global variable through a function without passing it to the function?
- How to put a variable into an array in Python
- Why is the CBS Sports app not working on Xbox?