Learning Python: Variable Scope
When a variable is declared, it is accessible in areas of the program that are after where was it declared. For example, if you declare a variable outside of a function, the variable then becomes accessible to code that is run in the function.
Examples
number = 9 def myfunction(): print(number) print(number) # 9 myfunction() # 9
The variable number
above is what is called a global variable. If we want the number
variable to be accessible only inside the function, that is called a local variable.
def myfunction(): number = 9 print(number) # 9 myfunction() # 9 print(number) # NameError: name 'number' is not defined.
This blog post was originally published on my blog Communicode, where I write about different tech topics.