Overview: Local Variables in Python
Suppose a function needs a variable only for its own work. If that variable is available throughout the program, other parts of the program can also access or change it even when they do not need it. This may lead to unexpected results.
To solve this problem, Python provides local variables.
Introduction: What Are Local Variables in Python?
Definition: Local variables are variables that Python creates inside a function. Because they are created inside a function, they belong to the local scope and can normally be accessed only within that function.
Local variables are useful when a value is needed only while a function performs a specific task. Instead of making the variable available throughout the program, the variable remains limited to the function where it is used.
For example, a function may need temporary values for a calculation, such as a price, quantity, or total. These values can be stored in local variables because they are needed only while that function performs its task.
How to Create Local Variables
The scope of a local variable is limited to the function where you create it. To create one, follow these steps:
- Define the variable inside a function.
- Assign a value to the variable.
- Use the variable within the function.
def greet():
message = "Hello"
print(message)
greet()
# Output:
Hello
Explanation: Here, the message variable is created inside the greet() function, so it is a local variable. The function can access and use message while it runs.
Accessing a Local Variable Inside a Function
A function can access a local variable when it is created inside that function. Let’s understand this with a simple example:
def calculate_total():
price = 500
quantity = 2
total = price * quantity
print(total)
calculate_total()
# Output:
1000
Explanation: Here, price, quantity, and total are local variables. The function uses these variables to calculate and display the total.
What Happens to a Local Variable Outside the Function?
What happens if code outside the function tries to access a local variable? Let’s see:
def greet():
message = "Hello"
greet()
print(message)
# Error:
NameError: name 'message' is not defined
Explanation: Here, code outside the function tries to access a local variable and Python raises a NameError. This happens because message exists only in the local scope of greet().
Rules of Local Variables in Python
Here are the main rules to remember when working with local variables in Python:
- A local variable is created inside a function.
- A local variable can be accessed only within the function where it is created.
- Each function has its own local variables, even when different functions use the same variable name.
- A local variable is created when the function executes the statement that assigns its value.
- A local variable is normally no longer available after the function finishes.
Use Cases of Local Variables
Here are some of the important use cases of local variables in Python:
- Storing values needed only inside a function
- Keeping temporary data within a function
- Performing calculations inside a function
- Processing data within a function
- Using the same variable name independently in different functions
Practical Examples: Local Variables in Python
The following examples will help you understand how local variables in Python are used in practical situations:
Example 1: Local Configuration Inside a Function
def calculate_price():
tax_rate = 0.05
price = 1000
return price + (price * tax_rate)
print(calculate_price())
# Output:
1050.0
Explanation: When calculate_price() runs, Python creates tax_rate and price inside the function. The function uses these local variables to calculate the final price and returns 1050.0. They are not needed outside the function.
Example 2: Local Variable for a Temporary Calculation
def calculate_area(length, width):
area = length * width
return area
print(calculate_area(10, 5))
# Output:
50
Explanation: When calculate_area(10, 5) runs, Python creates the local area variable and assigns it the result of the calculation. The function returns 50, and the local variable is no longer available after the function finishes.
Example 3: Processing Data Inside a Function
def format_name(first_name, last_name):
full_name = first_name + " " + last_name
return full_name
print(format_name("John", "Smith"))
# Output:
John Smith
Explanation: When format_name("John", "Smith") runs, Python creates the local full_name variable and combines the two names. The function returns "John Smith", while full_name remains local to the function.
Example 4: Using the Same Variable Name in Different Functions
def calculate_area():
result = 50 * 20
print("Area:", result)
def calculate_price():
result = 100 * 5
print("Price:", result)
calculate_area()
calculate_price()
# Output:
Area: 1000
Price: 500
Explanation: When calculate_area() runs, Python creates its local result and prints 1000. When calculate_price() runs, Python creates a separate local result and prints 500. The two variables belong to different functions, so they remain independent.
Example 5: Using Local Variables to Calculate a Final Result
def calculate_discount(price):
discount_rate = 0.10
discount = price * discount_rate
final_price = price - discount
return final_price
print(calculate_discount(1000))
# Output:
900.0
Explanation: When calculate_discount(1000) runs, Python creates the local discount_rate, discount, and final_price variables. The function uses them to calculate 900.0 and returns the result. All three variables remain local to calculate_discount().
Common Mistakes With Local Variables
Here are some common mistakes to avoid when working with local variables in Python.
1. Using a Local Variable Before Assignment
count = 10
def increase():
count = count + 1
print(count)
increase()
# Error:
UnboundLocalErrorExplanation: Because the function assigns a value to count, Python treats count as a local variable.
The function therefore tries to read the local variable before it has a value.
2. Accidentally Creating a Local Variable With the Same Name
count = 10
def update_count():
count = 20
print(count)
update_count()
print(count)
# Output:
20
10Explanation: The count created inside update_count() is a local variable. It has the same name as the global count, but it does not change the global variable.
The function prints 20, while the global variable remains 10.
Note: The concepts covered in this tutorial on local variables will be clearer once you understand global variables and the related topics below.
Related Topics
Some local-variable concepts also apply to global variables. These shared topics are covered separately to avoid repeating the same explanation.
Key Takeaways: Local Variables
Here are the key points to remember about local variables in Python:
- Local variables belong to the function where they are created.
- They can normally be accessed only within that function.
- Different functions can use the same variable name without affecting each other’s local variables.
- Trying to access a local variable outside its function can raise a
NameError. - Keeping function-specific variables local helps prevent unwanted interference with other parts of a program.