Python Tutorials

Python Functions : Def, Parameters & Return

As your Python programs grow larger, you will inevitably find yourself writing the exact same blocks of code over and over again. Imagine building an e-commerce app where you need to calculate sales tax. If you write the tax calculation formula in fifty different places, what happens when the tax rate changes? You would have to manually find and update all fifty lines of code.

To solve this, programmers use the DRY Principle (Don’t Repeat Yourself). Instead of repeating code, we package that logic into a reusable block called a Function. You write the code once, give it a descriptive name, and then “call” that name whenever you need the computer to perform that specific task. Functions are the foundational building blocks of organized, professional, and scalable software.

What is Defining Function?

In computer science, a Function is a named, self-contained block of organized, reusable code that is used to perform a single, related action.

  • def Keyword: The Python keyword used to define (create) a function.
  • Parameters/Arguments: The inputs a function accepts to perform its task dynamically.
  • Return Statement: The mechanism a function uses to send the processed data (the output) back to the main program.

Syntax & Basic Usage

To build a function in Python, you start with the def keyword, followed by your custom function name (using lowercase letters and underscores), parentheses (), and a colon :.

The code inside the function must be indented. Importantly, defining a function does not run the code. To execute the function, you must “call” it by typing its name followed by parentheses.

# 1. Defining the function
def display_welcome_message():
    print("Welcome to our application!")
    print("Initializing system systems...")

# 2. Calling the function (Execution happens here)
display_welcome_message()

# Expected Output:
# Welcome to our application!
# Initializing system systems...
Code language: PHP (php)

Exhaustive Exploration & Methods

While basic functions are helpful, their true power comes from accepting dynamic inputs and generating outputs. Let’s explore every feature of Python functions.

1. Parameters and Arguments (Passing Data In)

To make a function dynamic, you give it parameters. Parameters act as temporary variables inside the function’s parentheses. When you actually call the function, the real data you pass into it are called arguments.

# 'customer_name' is the parameter
def greet_customer(customer_name):
    print(f"Hello, {customer_name}! Thank you for your purchase.")

# "Alice" and "Bob" are the arguments
greet_customer("Alice")
greet_customer("Bob")

# Expected Output:
# Hello, Alice! Thank you for your purchase.
# Hello, Bob! Thank you for your purchase.
Code language: PHP (php)

2. The return Statement (Giving Data Back)

A common beginner mistake is using print() to output results inside a function. But print() only displays data on the screen; it doesn’t save it. If you want your function to calculate something so you can use the result later in your code, you must use the return keyword.

def calculate_annual_salary(monthly_wage):
    yearly_total = monthly_wage * 12
    # The return statement hands the data back to the program
    return yearly_total

# We capture the returned data inside a new variable
alices_salary = calculate_annual_salary(5000)
bobs_salary = calculate_annual_salary(4200)

print(f"Alice makes ${alices_salary} per year.")
print(f"Bob makes ${bobs_salary} per year.")

# Expected Output:
# Alice makes $60000 per year.
# Bob makes $50400 per year.
Code language: PHP (php)

3. Default Parameters (Optional Arguments)

You can assign a default value to a parameter in your function definition. If the programmer calling the function forgets to provide an argument, Python will safely fall back on the default value instead of crashing.

# 'account_status' defaults to "Active" if not explicitly provided
def create_user_profile(username, account_status="Active"):
    print(f"User: {username} | Status: {account_status}")

# Providing both arguments
create_user_profile("TechGuru", "Suspended")

# Providing only the required argument (relies on default)
create_user_profile("NewCoder")

# Expected Output:
# User: TechGuru | Status: Suspended
# User: NewCoder | Status: Active
Code language: PHP (php)

4. Keyword Arguments

Normally, arguments must be passed in the exact mathematical order as the parameters. However, you can use Keyword Arguments to explicitly state which parameter receives which value, meaning the order no longer matters!

def book_flight(destination, seat_class, meal_preference):
    print(f"Flight to {destination} | Class: {seat_class} | Meal: {meal_preference}")

# Using keyword arguments out of order
book_flight(meal_preference="Vegetarian", destination="Tokyo", seat_class="Economy")

# Expected Output:
# Flight to Tokyo | Class: Economy | Meal: Vegetarian
Code language: PHP (php)

5. Arbitrary Positional Arguments (*args)

What if you want to write a function that calculates the sum of expenses, but you don’t know if the user will pass in 2 expenses or 20 expenses? By placing an asterisk * before a parameter (conventionally named *args), Python collects all provided arguments into a Tuple.

# The * tells Python to pack all incoming positional arguments into a tuple
def calculate_total_expenses(*expense_amounts):
    total = sum(expense_amounts)
    return total

monthly_total = calculate_total_expenses(45.50, 120.00, 15.99, 8.50)

print(f"Total expenses this month: ${monthly_total}")

# Expected Output:
# Total expenses this month: $189.99
Code language: PHP (php)

6. Arbitrary Keyword Arguments (**kwargs)

Similar to *args, double asterisks ** (conventionally named **kwargs) allow you to pass an unknown number of Keyword Arguments. Python collects these into a Dictionary.

# The ** tells Python to pack incoming keyword arguments into a dictionary
def build_employee_record(first_name, last_name, **additional_details):
    record = {
        "first": first_name,
        "last": last_name
    }
    # We update the base dictionary with the flexible **kwargs dictionary
    record.update(additional_details)
    return record

# We can add as many random attributes as we want!
employee_one = build_employee_record("Jane", "Doe", role="Manager", office="NYC")

print(employee_one)

# Expected Output:
# {'first': 'Jane', 'last': 'Doe', 'role': 'Manager', 'office': 'NYC'}
Code language: PHP (php)

Real-World Practical Examples

Scenario 1: A E-Commerce Checkout Calculator

This function handles complex logic for calculating discounts and taxes, making the main program incredibly clean.

def calculate_final_checkout(cart_subtotal, discount_code=None):
    # 1. Apply discount if valid
    if discount_code == "SAVE20":
        cart_subtotal *= 0.80  # 20% off
    elif discount_code == "HALF_OFF":
        cart_subtotal *= 0.50  # 50% off
        
    # 2. Add fixed 8% sales tax
    tax_amount = cart_subtotal * 0.08
    final_total = cart_subtotal + tax_amount
    
    # 3. Return the exact value rounded to 2 decimal places
    return round(final_total, 2)

# Using the function in our app
customer_a_total = calculate_final_checkout(100.00, "SAVE20")
customer_b_total = calculate_final_checkout(100.00)

print(f"Customer A pays: ${customer_a_total}")
print(f"Customer B pays: ${customer_b_total}")

# Expected Output:
# Customer A pays: $86.4
# Customer B pays: $108.0
Code language: PHP (php)

Scenario 2: Data Cleaning and Validation

Functions are heavily used to clean messy user inputs before saving them to a database.

def clean_email_address(raw_email):
    # Strip whitespace and convert to lowercase
    cleaned_email = raw_email.strip().lower()
    
    # Basic validation check
    if "@" in cleaned_email and "." in cleaned_email:
        return cleaned_email
    else:
        return "Invalid Email"

# Simulating messy inputs
messy_input_1 = "   Admin@WEBSITE.com   "
messy_input_2 = "just_a_random_string"

print("Cleaned 1:", clean_email_address(messy_input_1))
print("Cleaned 2:", clean_email_address(messy_input_2))

# Expected Output:
# Cleaned 1: admin@website.com
# Cleaned 2: Invalid Email
Code language: PHP (php)

Best Practices & Common Pitfalls

  • Printing vs. Returning: The absolute most common beginner mistake. A function that calculates something should almost always use return. If you use print(), the data flashes on the screen but vanishes from the computer’s memory, meaning you cannot save it to a variable or use it in further math.
  • The Mutable Default Parameter Bug: NEVER use an empty list [] or dictionary {} as a default parameter (e.g., def add_item(item, my_list=[]):). Because of how Python handles memory, that list is shared across every single execution of the function, creating disastrous overlapping data bugs. Instead, use def add_item(item, my_list=None): and create the empty list inside the function.
  • Naming Conventions: Use lowercase letters and underscores (snake_case) for function names. Because functions perform actions, their names should almost always start with a verb (e.g., calculate_tax(), get_user(), parse_data()).
  • Do One Thing Well: A function should only do one specific job. If you have a function called fetch_data_and_calculate_tax_and_send_email(), it is doing too much. Break it down into three smaller, separate functions!

Summary

  • The def keyword is used to define a new function in Python.
  • Parameters are the variables defined inside the function’s parentheses; Arguments are the actual data values passed into the function when you call it.
  • Use the return statement to send processed data back out of the function so your program can store it in a variable.
  • Default parameters allow you to make arguments optional.
  • Keyword arguments allow you to pass data in any order by explicitly stating the parameter’s name.
  • *args (tuples) and **kwargs (dictionaries) allow a function to flexibly accept an unlimited number of incoming arguments.

Leave a Comment