Python Functions & Scope
Functions help us organise Python code into small, reusable blocks. Scope decides where a variable can be accessed. Together, these concepts make applications easier to maintain, test and understand.
- How to define and call functions.
- Parameters, arguments and return values.
- Default, keyword and variable-length arguments.
- Local, global and nonlocal scope.
- How Python resolves variable names using the LEGB rule.
1. What Is a Function?
A function is a reusable block of code that performs a specific task. Instead of writing the same logic repeatedly, we define it once and call it whenever required.
For example, an order-processing application may need to calculate the final amount for many orders. We can place that calculation inside one function.
def calculate_total(price, quantity):
total = price * quantity
return total
amount = calculate_total(250, 3)
print("Order total:", amount)
Order total: 750
def starts a function definition. The function name is calculate_total. Its parameters receive values, and return sends the result back to the caller.
2. Parameters and Arguments
Parameters are variable names listed in the function definition. Arguments are the actual values supplied when calling the function.
def create_user(name, role):
print(f"{name} - {role}")
# Positional arguments
create_user("Ananya", "Developer")
# Keyword arguments
create_user(role="Tester", name="Rahul")
Ananya - Developer Rahul - Tester
Default Parameters
A default parameter provides a value when the caller does not pass an argument for that parameter.
def send_notification(message, channel="email"):
print(f"Sending {message} through {channel}")
send_notification("Payment received")
send_notification("Order shipped", "SMS")
Sending Payment received through email Sending Order shipped through SMS
3. Variable-Length Arguments
Sometimes we do not know how many arguments a function will receive. Python supports *args and **kwargs for these situations.
Using *args
*args collects additional positional arguments into a tuple.
def calculate_bill(*amounts):
total = sum(amounts)
return total
print(calculate_bill(120, 250, 80))
450
Using **kwargs
**kwargs collects additional keyword arguments into a dictionary.
def display_employee(**details):
for key, value in details.items():
print(f"{key}: {value}")
display_employee(name="Meera", role="Architect", city="Bengaluru")
name: Meera role: Architect city: Bengaluru
4. Return Values
A function can return a value to the code that called it. This allows the caller to store the result, pass it to another function or use it in a calculation.
def get_order_summary(price, quantity):
subtotal = price * quantity
tax = subtotal * 0.18
return subtotal, tax
subtotal, tax = get_order_summary(1000, 2)
print("Subtotal:", subtotal)
print("Tax:", tax)
Subtotal: 2000 Tax: 360.0
Python returns multiple values as a tuple. In this example, the tuple is unpacked into two variables.
5. What Is Variable Scope?
Scope defines the region of a program where a variable name can be accessed. A variable created inside a function normally belongs to that function's local scope.
def process_payment():
payment_status = "Successful"
print(payment_status)
process_payment()
# This would raise NameError:
# print(payment_status)
Successful
The variable payment_status is local to process_payment(). It cannot normally be accessed directly outside that function.
6. Global Scope and the global Keyword
A variable defined at the module level is available throughout that module. A function can read a global variable directly. To reassign that global name inside a function, use the global keyword.
application_name = "Upgradix"
def show_application():
print(application_name)
def update_application():
global application_name
application_name = "Upgradix Learning"
show_application()
update_application()
show_application()
Upgradix Upgradix Learning
7. Enclosing Scope and the nonlocal Keyword
When a function is defined inside another function, the inner function can access names from the enclosing function. To reassign an enclosing variable, use nonlocal.
def create_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
counter = create_counter()
print(counter())
print(counter())
print(counter())
1 2 3
The inner function remembers the enclosing variable even after create_counter() has finished. This behaviour is closely related to closures.
8. Understanding the LEGB Rule
When Python needs to resolve a variable name, it searches through four levels in a specific order. This is called the LEGB rule.
| Level | Meaning | Example |
|---|---|---|
| Local | Current function | Variable inside a function |
| Enclosing | Outer function | Variable in a nested function's parent |
| Global | Module level | Variable defined outside functions |
| Built-in | Python built-ins | print, len, sum |
message = "Global"
def outer():
message = "Enclosing"
def inner():
message = "Local"
print(message)
inner()
outer()
print(message)
Local Global
The inner function finds message in its local scope first. The final print runs at module level and reads the global variable.
9. Functions Are First-Class Objects
In Python, functions are objects. You can assign them to variables, pass them as arguments and return them from other functions.
def calculate_discount(price):
return price * 0.10
def apply_discount(price, discount_function):
discount = discount_function(price)
return price - discount
final_price = apply_discount(1000, calculate_discount)
print(final_price)
900.0
This approach is useful when the calculation strategy should be supplied by the caller. It is also a foundation for decorators and callback-based designs.
10. Lambda Functions
A lambda is a small anonymous function containing a single expression. It is useful for short operations, especially when passing a function to another operation.
calculate_tax = lambda amount: amount * 0.18
print(calculate_tax(1000))
orders = [("ORD-03", 500), ("ORD-01", 200), ("ORD-02", 350)]
orders.sort(key=lambda order: order[1])
print(orders)
180.0
[('ORD-01', 200), ('ORD-02', 350), ('ORD-03', 500)]
Use a normal def function when the logic needs multiple statements, documentation or meaningful reuse.
11. Common Mistakes and Best Practices
- Forgetting return: A function that only prints a result does not return that result.
- Confusing arguments and parameters: Parameters appear in the definition; arguments are passed during a call.
- Unexpected global updates: Use global only when module-level reassignment is genuinely required.
- Mutable default values: Avoid defaults such as items=[] because the same list can be reused across calls.
- Too many responsibilities: Keep each function focused on one clear task.
- Unclear names: Prefer names such as calculate_total over vague names such as do_task.
12. Practice Exercise
Create a function named calculate_salary that accepts basic salary and bonus percentage. Return the final salary.
Then create another function that accepts any number of salary values using *args and returns their total.
Challenge: Use a nested function with nonlocal to maintain a count of processed employees.
13. Interview Questions
Conclusion
Functions make Python programs reusable and easier to organise. Scope controls how names are accessed and updated. Once you understand parameters, return values, local and global variables, nested functions and LEGB, you can write cleaner and more predictable Python applications.