Local Variables
In Python, a local variable is a variable that is defined
inside a function and can only be used within that function. It exists
only while the function is running, and it disappears after the function
finishes execution.
def greet():
message =
"Hello, World!" # 'message' is
a local variable
print(message)
greet()
# print(message) #
This would cause an error because 'message' is not accessible here
NOTES:
- message
is a local variable because it's defined inside the greet()
function.
- You cannot
access message outside the function.
- Local
variables are created when the function is called and are destroyed when
the function ends.
Why use local variables?
- To keep
data private to the function.
- To avoid
conflicts with variables in other parts of the program.
Global Variables
A global variable is a variable that is defined
outside of any function and can be accessed from anywhere in the program.
message = "Hello, World!" # This is a global variable
def greet():
print(message) # Accessing the
global variable inside the function
greet()
print(message) # Also
accessible outside the function
output:
Hello, World!
Hello, World!
Modifying
Global Variables Inside a Function:
If you want to change the value of a global variable
inside a function, you must use the global keyword:
count = 0 # Global
variable
def increment():
global count
count += 1 # Modifying the global variable
increment()
print(count) #
Output: 1
| Local Variable | Global Variable |
|---|---|
| Defined inside a function | Defined outside any function |
| Accessible only in function | Accessible throughout the program |
| Created when function runs | Created when program starts |
| Destroyed after function ends | Exists until program ends |
Global
& Local Variables
1. What is Scope?
The scope of a variable refers to the part of the program where
that variable is accessible. Python has two main types of variable scope:
•
Local Scope — The variable is declared inside a function and can
only be accessed within that function.
2. Global Variables
A global variable is declared outside any function. It can be
read and used from any part of the program — inside or outside functions.
Key properties:
•
Declared outside all functions
•
Accessible throughout the entire program
•
Exists for the entire duration of the program
•
Shared across multiple functions
Example:
|
# Global variable school = "Lotus
Valley School" def student_info(): print("School:", school) # global variable accessible here student_info() print("School:",
school) # accessible here too |
|
School: Lotus Valley School School: Lotus Valley School |
3. Local Variables
A local variable is declared inside a function. It only exists
while that function is running and cannot be accessed outside of it.
•
Declared inside a function
•
Only accessible within that function
•
Created when the function is called
•
Destroyed (deleted) when the function ends
Example:
|
def student_info(): name = "Priya" # local variable marks = 92 # local variable print("Name:", name) print("Marks:", marks) student_info() # print(name) <-- ERROR! name is local, doesn't exist
here |
|
Name: Priya Marks: 92 |
4. The global Keyword
By default, if you assign a value to a variable inside a function, Python treats it as a new local variable. To modify a global variable from inside a function, you must use the global keyword.
|
Without the global keyword, Python creates a NEW local
variable instead of modifying the global one. This is a very common mistake! |
Example:
|
counter = 0 # global variable def increment(): global counter # tell Python: use the global
counter counter = counter + 1 print("Counter:", counter) increment() increment() increment() print("Final:",
counter) |
Output:
|
Counter: 1 Counter: 2 Counter: 3 Final: 3 |
5. Same Variable Name — Variable Shadowing
A local variable can have the same name as a global variable.
Inside the function, the local variable shadows (hides) the global one. They
are completely separate variables.
Example:
|
colour =
"Blue" # global variable def paint_wall(): colour = "Yellow" # local variable (separate from global) print("Inside function:",
colour) paint_wall() print("Outside function:",
colour) # global unchanged |
Output:
|
Inside function: Yellow Outside function: Blue |
|
This concept is called variable shadowing. The local variable
hides the global one inside the function but NEVER modifies it. Mention this
term in exams for extra marks! |
6. Common Error — NameError
If you try to access a local variable outside its function,
Python throws a NameError because the variable no longer exists.
Example:
|
def calculate(): result = 100 + 200 # local variable print("Result inside:", result) calculate() print(result) # NameError! result was destroyed after
function ended |
Output:
|
Result inside: 300 NameError: name 'result'
is not defined |
|
Fix: Use return to pass the value back: return result, then
capture it outside: answer = calculate() |
7. Quick Summary Table
|
Feature |
Global
Variable |
Local
Variable |
|
Declared |
Outside any function |
Inside a function |
|
Accessible |
Entire program |
That function only |
|
Lifetime |
Entire program run |
During function call only |
|
Modify from function? |
Only with global keyword |
Directly (no keyword needed) |
|
Memory usage |
More (stays in memory) |
Efficient (freed after use) |
8. Important Rules to Remember
•
Read vs Write: A
function can read a global variable freely. To write (modify) it, use the
global keyword.
•
Temporary: Local
variables are created when a function is called and destroyed when it returns.
•
Independence: Two
variables with the same name (one global, one local) are completely separate.
•
Avoid globals: Too
many global variables make code hard to debug. Prefer passing values as
parameters.
•
NameError: Accessing
a local variable outside its function always causes a NameError.
9. Practice Questions
1.
What is the difference between a global and a local variable?
Give one example of each.
2.
Write a Python program that uses the global keyword to count how
many times a function has been called.
3.
What error occurs if you try to access a local variable outside
its function? Why does this happen?
4.
If a global variable and a local variable have the same name,
which one is used inside the function? Explain with an example.
Comments
Post a Comment