Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
Why Functions?Parameters & ArgumentsReturn StatementsScopeDefault ParametersVariable Arguments (*args)Lambda FunctionsDecoratorsFunctional ProgrammingBest Practices
Python/Functions/Best Practices

✨ Best Practices — Writing Good Functions

Good functions are easy to understand, easy to use, and easy to fix when something goes wrong.


🎯 1. Give Functions Clear Names

A function's name is the first thing someone sees when reading your code, so it should tell them exactly what it does. Use action verbs like "calculate", "get", "check", or "display" followed by what the function operates on. Avoid vague names like "process", "handle", or "do_thing" that don't tell you anything meaningful.

# ❌ Bad names
def process(x):
    return x * 2

def do_thing():
    print("Hello")

# ✅ Good names
def double_number(x):
    return x * 2

def greet_user():
    print("Hello")

📝 2. Keep Functions Small

Functions should have a single, focused responsibility—they do one job and do it well. When functions try to do too much, they become hard to understand, hard to test, and hard to reuse. If you find yourself naming a function with multiple verbs or using "and" in the description, it's a sign you should split it into smaller functions.

# ❌ Bad - does too much
def process_user(name, age, email):
    print(name)
    print(age)
    print(email)
    send_email(email)
    save_to_database(name)

# ✅ Good - each function does one thing
def display_user(name, age, email):
    print(name)
    print(age)
    print(email)

def notify_user(email):
    send_email(email)

def save_user(name):
    save_to_database(name)

💡 3. Use Good Parameter Names

Parameters are like instructions to whoever calls your function, so make them as clear as possible. Instead of single letters like `a` or `x`, use descriptive names that tell you what kind of data is expected. This makes your function self-documenting and much easier for others to use correctly without having to read the code inside.

# ❌ Confusing
def calc(a, b):
    return a * b

# ✅ Clear
def calculate_area(width, height):
    return width * height

📚 4. Write Docstrings

A docstring is a multi-line comment that appears right after the function definition and explains what it does, what parameters it takes, and what it returns. Docstrings are especially important because they appear in help text and documentation tools. Writing good docstrings saves time for anyone using your function—including yourself when you come back to the code months later.

def celsius_to_fahrenheit(celsius):
    """
    Convert temperature from Celsius to Fahrenheit.

    Args:
        celsius: Temperature in Celsius (number)

    Returns:
        Temperature in Fahrenheit (number)
    """
    return (celsius * 9/5) + 32

✅ 5. Keep Functions Predictable

Callers of your function should know what type of value to expect back. If your function sometimes returns a number, sometimes a string, and sometimes nothing, code that calls it becomes fragile and error-prone. Make your functions predictable by always returning the same type, or by using `None` as a consistent "no result" value. This makes your code more reliable and easier to debug.

# ❌ Bad - sometimes returns string, sometimes number
def find_user(name):
    if name:
        return 25  # Returns number
    else:
        return "Not found"  # Returns string!

# ✅ Good - always returns same type
def find_user_age(name):
    if name:
        return 25
    else:
        return None  # Returns same type (or None)

🚫 6. Avoid Side Effects

Side effects are when a function changes something outside of itself, like modifying a global variable or writing to a file. Functions with side effects are unpredictable and hard to test because they affect other parts of your program in hidden ways. The best functions take inputs, compute a result based only on those inputs, and return the result without changing anything else.

global_list = []

# ❌ Bad - changes global list
def add_item(item):
    global_list.append(item)

# ✅ Good - returns new list
def add_item(item, items=None):
    if items is None:
        items = []
    return items + [item]

🔑 Best Practices Checklist

✅ Clear, descriptive name
✅ Does one thing
✅ Good parameter names
✅ Has a docstring
✅ Consistent return type
✅ No side effects
✅ Small and simple
✅ Easy to test

🔑 Key Takeaways

PracticeWhy
Clear namesEasy to understand
One responsibilityEasy to test and fix
Good parameter namesEasy to use
DocstringsEasy to learn
Consistent typesNo surprises
No side effectsPredictable behavior

🔗 What's Next?

You've completed all the fundamental and practical concepts for functions! Keep practicing with challenges and challenges to master them.

Back to Functions Overview →


Ready to practice? Try challenges or view solutions


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn