🧩 Mastering User-Defined Functions in Python: Real-World Examples

PYTHON

5/5/20253 min read

Python’s real power comes from its ability to let you define your own functions — reusable blocks of code that make your programs cleaner, modular, and easier to debug.

In this post, we’ll explore user-defined functions (UDFs) with practical use cases across data processing, validation, and automation.

🧠 What Is a User-Defined Function?

A user-defined function is a named block of reusable code that performs a specific task. You define it with the def keyword.

Basic Syntax:

def function_name(parameters):

# code block

return result

✅ Why Use Functions?
  • 📦 Reuse code instead of repeating it

  • 🧼 Make code cleaner and easier to debug

  • 🔁 Handle tasks dynamically with parameters

  • 📊 Abstract logic in data pipelines or scripts

🔧 Example 1: Clean Customer Names

Let’s say you're cleaning a messy dataset of customer names:

def clean_name(name):

name = name.strip().lower().title()

return name

print(clean_name(" JOHN doe ")) # John Doe

🔍 Example 2: Validate Email Format

Basic email validation using @ and .

def is_valid_email(email):

return "@" in email and "." in email

print(is_valid_email("alice@example.com")) # True

🛠 Example 3: Generate Custom Filenames

def generate_filename(name, date):

name = name.replace(" ", "_").lower()

return f"{name}_{date}.csv"

filename = generate_filename("Sales Report", "2025-05-01")

💡 Tips for Writing Better Functions
  • Use clear names for functions and parameters

  • Keep them short and focused

  • Use default parameters when needed

  • Return values rather than printing them inside

  • Add docstrings to describe what the function does

🧪 Bonus: Test Your Functions

def square(n):

return n * n

# Simple test

assert square(3) == 9

assert square(0) == 0

✅ Helps you catch bugs early when logic changes.

✨ Summary

User-defined functions aren’t just for coders — they’re a data analyst’s secret weapon for clean, reusable, and readable code.

Kishore Babu Valluri

Senior Data Scientist | Freelance Consultant | AI/ML & GenAI Expert

With deep expertise in machine learning, artificial intelligence, and Generative AI, I work as a Senior Data Scientist, freelance consultant, and AI agent developer. I help businesses unlock value through intelligent automation, predictive modeling, and cutting-edge AI solutions.

💸 Example 4: Calculate Discounted Price

import numpy as np

def calculate_discounted_price(price, discount_percent):

discounted_price = price - (price * discount_percent / 100)

return np.round(discounted_price, 2)

# Example

print(calculate_discounted_price(100, 10)) # Output: 90.0

🧮 Example 5: Calculate Total Revenue from a List of Sales

def calculate_total_revenue(sales):

total = 0

for sale in sales:

total += sale['quantity'] * sale['unit_price']

return total

# Example

sales_data = [

{'item': 'Laptop', 'quantity': 3, 'unit_price': 800},

{'item': 'Mouse', 'quantity': 10, 'unit_price': 25},

]

print(calculate_total_revenue(sales_data)) # Output: 2550

🚩 Example 6: Function to Flag Low-Performing Products

def flag_low_sales(sales, threshold):

low_performers = []

for item in sales:

revenue = item['quantity'] * item['unit_price']

if revenue < threshold:

low_performers.append(item['item'])

return low_performers

# Example

print(flag_low_sales(sales_data, 500)) # Output: ['Mouse']

🏆 Example 7: Get Top N Selling Items

def get_top_selling_items(sales, n):

sales.sort(key=lambda x: x['quantity'] * x['unit_price'], reverse=True)

return sales[:n]

# Example

top_items = get_top_selling_items(sales_data, 1)

print(top_items) # [{'item': 'Laptop', 'quantity': 3, 'unit_price': 800}]

Explanation:

sales.sort(key=lambda x: x['quantity'] * x['unit_price'], reverse=True)

To sort a list of sales records (dictionaries), in descending order of total revenue per item (i.e., quantity × unit_price).

Step-by-Step Breakdown:

🔹 1. sales.sort(...) – Sort the List In-Place
  • .sort() is a method for lists in Python.

  • It modifies the original list directly (doesn’t create a new one).

  • The optional arguments key and reverse customize the sort behavior.

🔹 2. key=lambda x: x['quantity'] * x['unit_price']

This is a custom key function. Here's what happens:

  • Python needs to compare items in the list to decide their order.

  • The key= argument tells it: “don’t compare the raw dictionaries—compare this derived value instead.”

Internally:
  • For each dictionary x in the list, Python calls the lambda function:

    lambda x: x['quantity'] * x['unit_price']

    This returns a single number: the revenue for that item.

  • So the key function transforms the original list into:

    [2400, 250, 500]

    Python then uses these numbers to determine sort order.

Python then uses these numbers to determine sort order.

🔹 3. reverse=True – Sort in Descending Order
  • By default, .sort() arranges in ascending order.

  • reverse=True flips it to descending, so the highest revenue items come first.

🧰 Summary of Internal Steps

Here’s what Python does under the hood:

  1. Iterates over each x in sales.

  2. Computes the key: x['quantity'] * x['unit_price'].

  3. Sorts the sales list using those key values.

  4. Reorders the list from highest to lowest revenue.