TutorialsPythonFunctions in Python

Functions in Python

Write reusable functions to avoid repeating logic across your analysis scripts

Functions package reusable logic under a name you can call anywhere. In data analysis, functions are used to standardise cleaning steps, apply complex business logic to columns, generate formatted reports, and structure your code so a notebook remains readable. The principle: if you write the same block of code twice, turn it into a function. Functions also make debugging easier — fix it in one place, it is fixed everywhere.

Examples

Define and call functions
# Basic function
def calculate_margin(revenue, cost):
    """Calculate profit margin as a percentage."""
    profit = revenue - cost
    return (profit / revenue) * 100

margin = calculate_margin(500000, 380000)
print(f"Margin: {margin:.1f}%")   # Margin: 24.0%

# Default arguments
def format_currency(amount, symbol="₹", in_lakhs=False):
    if in_lakhs:
        return f"{symbol}{amount/100000:.1f}L"
    return f"{symbol}{amount:,.0f}"

print(format_currency(450000))           # ₹4,50,000
print(format_currency(450000, in_lakhs=True))  # ₹4.5L

# Return multiple values
def summary_stats(data):
    return min(data), max(data), sum(data)/len(data)

low, high, avg = summary_stats([45, 72, 38, 91, 55])
print(low, high, avg)   # 38 91 60.2
💡 Docstrings (triple quotes below def) document what the function does — Python shows them with help(function_name).
Lambda functions and applying to DataFrames
import pandas as pd

df = pd.DataFrame({
    "First": ["Rahul", "Priya", "Amit"],
    "Last":  ["Sharma", "Singh", "Verma"],
    "Sales": [450000, 320000, 580000],
})

# Lambda — one-line anonymous function
double = lambda x: x * 2
print(double(5))   # 10

# Apply a function to a column
df["Full Name"] = df.apply(
    lambda row: row["First"] + " " + row["Last"], axis=1
)

# Apply a custom cleaning function
def clean_name(name):
    return name.strip().title()

df["First"] = df["First"].apply(clean_name)

# Apply to multiple columns
df["Sales (L)"] = df["Sales"].apply(lambda x: round(x/100000, 1))

Key Points

  • def function_name(parameters): — always colon and indented body
  • return sends a value back — without return, function returns None
  • Default arguments make parameters optional: def f(x, y=10)
  • Lambda functions are one-line anonymous functions for simple transformations
  • .apply(function) applies a function to every value in a Pandas Series or DataFrame row

Practice Question

What does a Python function return if it has no return statement?

Related Topics

Loops — for and whileIterate over data, automate repetitive tasks, and process multiple files with loopsConditionals — if, elif, elseWrite if/elif/else logic to categorise, flag and filter data in PythonPython Best Practices for Data AnalystsWrite clean, readable, professional Python code — habits that matter in team environments