Python - Using glob...
 
Share:
Notifications
Clear all

Python - Using global variables in a function


Neha
 Neha
(@asha)
Member Admin
Joined: 1 year ago
Posts: 27
Topic starter  

How can I create or use a global variable in a function?

If I create a global variable in one function, how can I use that global variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?


Govind and myTechMint liked
Quote
Topic Tags
myTechMint
(@mytechmint)
Member Moderator
Joined: 1 year ago
Posts: 31
 

You can use a global variable within other functions by declaring it as global within each function that assigns a value to it:

globvar = 0
def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = 1
def print_globvar():
print(globvar) # No need for global declaration to read value of globvar
set_globvar_to_one()
print_globvar() # Prints 1

I imagine the reason for it is that, since global variables are so dangerous, Python wants to make sure that you really know that's what you're playing with by explicitly requiring the global keyword.


Neha and Govind liked
ReplyQuote