Local and Global Variables in Python: Explained with Examples and Tasks
Learn the difference between local and global variables in Python with simple explanations, practical examples, and beginner-friendly tasks. Understand constants, best practices, and how to manage variables effectively in your programs.
Local Variables
What is a Local Variable?
Local variables are variables declared inside a function. They can only be accessed within that function and are destroyed when the function completes execution..
It only exists while the function is running.
You cannot use it outside the function.
Characteristics:
Created when the function starts
Only accessible within the function
Destroyed when the function exits
Example:
defgreet():message="Hello, world!"# local variable
print(message)greet()# This will cause an error:
# print(message)
message is local to greet() and canβt be accessed outside.
Key Points:
Local variables are created when the function starts.
They are destroyed when the function ends.
They do not affect variables outside the function.
PI=3.14159# This is a constant (by convention)
TAX_RATE=0.20# Another constant
defcalculate_tax(amount):returnamount*TAX_RATEprint(calculate_tax(100))# Output: 20.0
Best Practices:
Avoid excessive use of global variables as they can make code harder to maintain
Use ALL_CAPS for constants to indicate they shouldnβt be modified
When you must use global variables, declare them clearly at the top of your file
Tasks:
Task #1: Global Variable Task
Create a global variable called language set to "Python".
Write a function show_language() that prints "I love Python!" using the global variable.
Task #2:
Define a constant GRAVITY = 9.8.
Write a function weight_on_earth(mass) that calculates and returns the weight.
Task #3:
Create a program with:
A global constant DISCOUNT set to 0.10
A global variable total_purchases initialized to 0
A function make_purchase(amount) that adds to total_purchases and applies the discount
A function show_total() that prints the current total