Module: M3-R5: Python Programming
Chapter: Functions
A local variable is a variable that is declared and used inside a function. It exists only within that function’s scope and is destroyed once the function finishes execution.
Syntax:
def function_name():
variable_name = value # Local variable
print(variable_name)
def greet():
message = "Welcome to QuiteXams!" # Local variable
print(message)
greet()
# Trying to access it outside the function
print(message) # This will cause an error
Output:
Welcome to QuiteXams!
NameError: name 'message' is not defined
➡ The variable message is local to the function greet() and cannot be accessed outside.
x = 10 # Global variable
def show():
x = 5 # Local variable
print("Inside function:", x)
show()
print("Outside function:", x)
Output:
Inside function: 5
Outside function: 10
➡ Here, x inside the function is local and different from the global x.
Function parameters also behave as local variables within the function.
def add(a, b):
sum = a + b # sum, a, b are local variables
print("Sum:", sum)
add(4, 6)
print(a) # Error
Output:
Sum: 10
NameError: name 'a' is not defined
➡ Both a and b are local to add().
The lifetime of a local variable begins when the function is called and ends when the function execution is completed.
def demo():
x = 1
x += 1
print("x =", x)
demo()
demo()
Output:
x = 2
x = 2
➡ Each time the function runs, a new local copy of x is created.
| Feature | Description |
|---|---|
| Declared Inside Function | Yes |
| Accessible Outside Function | No |
| Lifetime | Created when function starts, destroyed when it ends |
| Example | def func(): x = 5 |