LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
Python

Python - Functions & Scope

Functions allow you to bundle statements into a named block that executes on demand, preventing repetitive code. With *args and **kwargs, your functions can accept any number of inputs. Understanding Python variable resolution rules ensures your variables stay isolated and never accidentally overwrite data across different parts of your application.

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.

What you will learn
  • 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.

Python – Defining and Calling a Function
def calculate_total(price, quantity):
    total = price * quantity
    return total

amount = calculate_total(250, 3)
print("Order total:", amount)
Expected Output
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.

Python – Different Ways to Pass Arguments
def create_user(name, role):
    print(f"{name} - {role}")

# Positional arguments
create_user("Ananya", "Developer")

# Keyword arguments
create_user(role="Tester", name="Rahul")
Expected Output
Ananya - Developer
Rahul - Tester

Default Parameters

A default parameter provides a value when the caller does not pass an argument for that parameter.

Python – Default Argument
def send_notification(message, channel="email"):
    print(f"Sending {message} through {channel}")

send_notification("Payment received")
send_notification("Order shipped", "SMS")
Expected Output
Sending Payment received through email
Sending Order shipped through SMS
Remember: Parameters with default values should normally appear after required parameters. Avoid mutable objects such as lists or dictionaries as default values unless shared state is intentional.

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.

Python – Variable Positional Arguments
def calculate_bill(*amounts):
    total = sum(amounts)
    return total

print(calculate_bill(120, 250, 80))
Expected Output
450

Using **kwargs

**kwargs collects additional keyword arguments into a dictionary.

Python – Variable Keyword Arguments
def display_employee(**details):
    for key, value in details.items():
        print(f"{key}: {value}")

display_employee(name="Meera", role="Architect", city="Bengaluru")
Expected Output
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.

Python – Returning Multiple Values
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)
Expected Output
Subtotal: 2000
Tax: 360.0

Python returns multiple values as a tuple. In this example, the tuple is unpacked into two variables.

Important: A function without an explicit return statement returns None. Printing a value and returning a value are different operations.

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.

Python – Local Scope
def process_payment():
    payment_status = "Successful"
    print(payment_status)

process_payment()

# This would raise NameError:
# print(payment_status)
Expected Output
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.

Python – Reading and Updating a Global Variable
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()
Expected Output
Upgradix
Upgradix Learning
Best practice: Avoid using global variables for frequently changing application state. Prefer function parameters, return values or well-designed objects.

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.

Python – nonlocal Example
def create_counter():
    count = 0

    def increment():
        nonlocal count
        count += 1
        return count

    return increment

counter = create_counter()

print(counter())
print(counter())
print(counter())
Expected Output
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.

PYTHON NAME RESOLUTION L — Local Inside the current function E — Enclosing Outer function scopes G — Global Current module namespace B — Built-in
Python checks Local, Enclosing, Global and Built-in namespaces in this order.
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
Python – LEGB in Action
message = "Global"

def outer():
    message = "Enclosing"

    def inner():
        message = "Local"
        print(message)

    inner()

outer()
print(message)
Expected Output
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.

Python – Passing a Function as an Argument
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)
Expected Output
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.

Python – Lambda Example
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)
Expected Output
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

Build a simple employee salary calculator.

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

1. What is the difference between a parameter and an argument? A parameter is defined in the function signature. An argument is the value passed during a function call.
2. What happens when a Python function has no return statement? It returns None by default.
3. What is the difference between global and nonlocal? global targets a module-level name. nonlocal targets a name in an enclosing function scope.
4. What is the LEGB rule? It is Python's name lookup order: Local, Enclosing, Global and Built-in.
5. What is a closure? A closure is an inner function that retains access to variables from its enclosing scope after the outer function has returned.
6. What is the difference between *args and **kwargs? *args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary.

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.

Next step: Practise writing small functions, passing functions as arguments and tracing variable lookup. These concepts will prepare you for decorators, closures and more advanced Python programming.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.