Variables in Python can be classified as local or global based on their scope (where they can be accessed in the program). Understanding the differences between these types of variables is crucial for writing clean and effective Python code.
Global variables are variables declared outside of any function or class. They can be accessed and modified throughout the program, including inside functions.
Scope: Global variables are accessible from any part of the code after they are defined, including functions, loops, or conditionals.
Example:
x = 10 # Global variable
def print_global():
print(x) # Accessing global variable inside a function
print_global() # Output: 10
Modifying Global Variables: If you want to modify a global variable inside a function, you must use the global
keyword.
x = 10 # Global variable
def modify_global():
global x # Indicating that we are referring to the global variable
x = 20 # Modifying the global variable
modify_global()
print(x) # Output: 20
Local variables are declared inside a function or a block of code. They are only accessible within the function where they are defined and cannot be accessed outside of it.
Scope: Local variables are only valid within the function or block they are created in. They are destroyed once the function finishes execution.
Example:
def my_function():
y = 5 # Local variable
print(y)
my_function() # Output: 5
# print(y) # This would raise an error: NameError: name 'y' is not defined
If a local variable and a global variable share the same name, Python will prioritize the local variable when referencing the variable within a function. The global variable will only be used outside the function or if explicitly declared as global
inside the function.
x = 10 # Global variable
def my_function():
x = 20 # Local variable
print(x) # Output: 20
my_function()
print(x) # Output: 10 (Global variable remains unchanged outside the function)
When working with global variables inside a function, you can either:
global
keyword).Example (Accessing):
x = 50 # Global variable
def print_value():
print(x) # Accessing global variable
print_value() # Output: 50
Example (Modifying):
x = 50 # Global variable
def modify_value():
global x
x = 100 # Modifying the global variable
modify_value()
print(x) # Output: 100
Limit the Use of Global Variables:
Prefer Local Variables for Function Logic:
Use Global Variables for Constants:
Avoid Modifying Global Variables Unnecessarily:
Objective: Understand the scope and behavior of local and global variables through practical examples.
Global Variable Modification:
call_count
that keeps track of the number of times a function is called. Each time the function is executed, increment call_count
and print its value.call_count = 0
def count_calls():
global call_count
call_count += 1
print(f"Function has been called {call_count} times.")
count_calls() # Output: Function has been called 1 times.
count_calls() # Output: Function has been called 2 times.
Local Variable Experiment:
calculate_square()
that takes a number as input, squares it using a local variable, and prints the result. Try to access the local variable outside the function and observe what happens.def calculate_square(num):
square = num ** 2 # 'square' is a local variable
print(f"Square of {num} is {square}")
calculate_square(5)
# print(square) # This will raise an error because 'square' is local to the function
Global and Local Variables with Same Name:
value = 10
. Inside a function, define a local variable value = 20
. Print both the global and local variables inside and outside the function to see how Python handles them.value = 10 # Global variable
def local_value():
value = 20 # Local variable
print(f"Inside the function, local value: {value}")
local_value() # Output: Inside the function, local value: 20
print(f"Outside the function, global value: {value}") # Output: Outside the function, global value: 10
Use Global Variable for Constants:
PI = 3.14159
and uses it in a function to calculate the area of a circle. Ensure that the constant cannot be modified inside the function.PI = 3.14159 # Global constant
def calculate_area(radius):
area = PI * (radius ** 2)
print(f"Area of the circle with radius {radius} is {area}")
calculate_area(5) # Output: Area of the circle with radius 5 is 78.53975