Setting a Local Python Variable to be Global

Python

We can set a local variable (i.e. one in a function) to be global by using the global keyword. This allows a global variable to be modified from within a non-global space or a local variable to be accessible outside the scope of the local space it's declared within.

 1|  def some_function()
 2|      global variable_name
 3|      variable_name = 'New Value'
 4|  
 5|  #Example:
 6|      
 7|  number = 42
 8|  def new_number():
 9|      global number 
10|      number = 43
11|  new_number()
Did you find this snippet useful?

Sign up for free to to add this to your code library