QNA > W > Why Is A Global Variable Not Changed In Python?

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 :

  1. >>> a = 17 
  2. >>> def func() 
  3. >>> a = 23 
  4. >>> print(2,a) 
  5. >>> print(1,a) 
  6. >>> func() 
  7. >>> print(3,a) 
  8. 1, 17 
  9. 2, 23 
  10. 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.

  1. >>> a = 17 
  2. >>> def func() 
  3. >>> global a 
  4. >>> a = 23 
  5. >>> print(2,a) 
  6. >>> print(1,a) 
  7. >>> func() 
  8. >>> print(3,a) 
  9. 1, 17 
  10. 2, 23 
  11. 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.

  1. >>> a = 17 
  2. >>> def func( value ) 
  3. >>> value = value +1 
  4. >>> print(2,value) 
  5. >>> return value 
  6. >>> print(1,a) 
  7. >>> a = func(a) 
  8. >>> print(3,a) 
  9. 1, 17 
  10. 2, 18 
  11. 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 :

  1. # module2.py 
  2. value = 17 
  3.  
  4. # module1.py 
  5. import module2 
  6. print( module2.value ) # you cannot simply use 'value' here. 
  7.  
  8. # module3.py 
  9. from module2 import value as value  
  10. # module2.value now can be called value 
  11. print( value )  

You can now run either module1 or module3 and get the value of 17 as output.

Di Egwin Trulock

Quali sono le migliori app per le coppie? :: Qual è il miglior registratore dello schermo del computer portatile?
Link utili