Variables Types in Python
There are following types of variables in Python:
• local variable
• global variable
1. Local variable A local variable is a variable that is defined within a function and is only accessible within that function. It is created when the function is called and is destroyed when the function returns.
We cannot use local variables in global scope.
Example:
Python
def greet(name): # 'message' is a local variable — exists only inside greet() message = f"Hello, {name}" print(message) greet("Ashish") # Output: Hello, Ashish # The variable 'message' is not defined here (outside the function): # print(message) # => NameError: name 'message' is not defined
2. Global variable A global variable is a variable that is defined outside of a function and is accessible from within any function in our code.
Example:
Python
# This is a global variable (module-level) x = 100 def read_global(): # We can read a global from inside a function without any keyword print("inside read_global:", x) read_global() # prints 100 print("outside:", x) # prints 100
In this example, we have a global variable x. We can access the value of the global variable x from within the function.
Note: Without using the global keyword, we can use the global variable in the local scope, but we cannot change the value of that global variable.
Example: Trying to change the global variable without global.
Python
x = 100 # Global variable def change_value(): # Python thinks 'x' is a local variable because we assign to it below x = x + 1 # ❌ Error: local variable 'x' referenced before assignment print("Inside function:", x) change_value()
Error: UnboundLocalError: local variable 'x' referenced before assignment
Global variable and Local variable with same name When we create the global variable and local variable with the same name, then the local variable hides the global variable in the local scope.
Example:
Python
x = 50 # Global variable def my_function(): x = 10 # Local variable with the same name as global print("Inside function (local x):", x) my_function() print("Outside function (global x):", x)
Note: If you want to modify the global variable even if there is a local with the same name, you must use the global keyword.