Skip to content

Module 9 · Functions — topic 19 of 19

Function best practices

Designing good functions: single responsibility, clear names, small size, few parameters, no hidden side effects, consistent return types, and refactoring long code into functions.

Beginner 12 min read·Lesson 144 of 306 in Python Programming

Learning objectives

  • Evaluate a function against common design guidelines
  • Refactor a long script into focused functions
  • Write pure functions where possible

Definition

Function best practices are design guidelines that make functions easy to read, test and reuse: each should do one thing, be named for what it does, take explicit inputs, return explicit outputs and avoid surprising side effects.

Introduction

Two programs can produce identical output while one is a pleasure to maintain and the other a nightmare. The difference is mostly in how the code is split into functions.

Why it matters

Projects grow, requirements change and bugs appear. Small, well-named, side-effect-free functions can be understood, tested and changed one at a time.

Detailed explanation

Single responsibility: a function should do one thing. If its name needs 'and' (load_and_clean_and_plot), split it.

Names: verbs for actions (calculate_total), is_/has_ for booleans (is_valid), nouns for values a function returns are also fine (average).

Size: if a function doesn't fit on one screen, it probably does too much. Aim for under about 20–30 lines.

Parameters: few and meaningful. Many parameters suggest the function does too much or needs an object to group them.

Pure functions depend only on their arguments and have no side effects (no printing, no global changes, no file writes). They are trivially testable. Keep input/output at the edges of the program and pure logic in the middle.

Return consistent types: don't return a list in one case and a string in another.

DRY (Don't Repeat Yourself): when you copy-paste code, extract a function instead.

Syntax

Python
# Pure logic
def apply_discount(total, percent):
return round(total * (1 - percent / 100), 2)
# I/O at the edges
def main():
total = float(input("Total: "))
print(apply_discount(total, 10))
  • One job per function.
  • Logic in pure functions; I/O in a thin outer layer.
  • Consistent return types.

Code examples

Splitting a function that does too much

Python
def parse_marks(text):
return [int(x) for x in text.split(",")]
def average(values):
return sum(values) / len(values)
def grade(avg):
return "A" if avg >= 90 else "B" if avg >= 75 else "C"
marks = parse_marks("92,88,71")
print(marks, round(average(marks), 1), grade(average(marks)))
Output
[92, 88, 71] 83.7 B

Pure functions are easy to test

Python
def apply_discount(total, percent):
return round(total * (1 - percent / 100), 2)
assert apply_discount(1000, 10) == 900.0
assert apply_discount(99.99, 0) == 99.99
assert apply_discount(250, 100) == 0.0
print("all checks passed")
Output
all checks passed

More examples

Refactoring a script into functions

Python
orders = ["Asha,pen,3,10", "Ravi,book,1,250", "Asha,book,2,250", "bad line"]
def parse(line):
"""Return (customer, item, quantity, price) or None for a malformed line."""
parts = line.split(",")
if len(parts) != 4:
return None
name, item, qty, price = parts
return name, item, int(qty), int(price)
def totals_by_customer(records):
totals = {}
for name, _, qty, price in records:
totals[name] = totals.get(name, 0) + qty * price
return totals
def format_report(totals):
return "\n".join(f"{name:<6}{amount:>6}" for name, amount in sorted(totals.items()))
def main():
records = [r for r in map(parse, orders) if r is not None]
print(format_report(totals_by_customer(records)))
print(f"{len(orders) - len(records)} line(s) skipped")
main()
Output
Asha     530
Ravi     250
1 line(s) skipped

Step-by-step explanation

  • parse handles exactly one line and reports bad input with None.
  • totals_by_customer is pure: given records, it returns a dictionary.
  • format_report only builds text; it doesn't print.
  • main wires the steps together and is the only function that prints — I/O stays at the edge.

Expected output

Running “Refactoring a script into functions” prints exactly:

TextOutput
Asha 530
Ravi 250
1 line(s) skipped

Practical applications

  • Code review checklists include function size, naming and side effects.
  • Test suites target pure functions first because they need no setup.

Best practices

  • One responsibility, a clear verb name, a docstring.
  • Keep logic pure and push printing/input to main().
  • Refactor duplicated code into functions as soon as you notice it.

Common mistakes

A function with hidden side effects

Avoid

def total(items):
items.sort() # surprise!
print(sum(items)) # caller can't reuse the value

Prefer

def total(items):
return sum(items)

Callers don't expect a 'total' function to reorder their list or print.

Inconsistent return types

Avoid

def find(users, name):
...
return "not found" # sometimes a dict, sometimes a str

Prefer

def find(users, name):
...
return None

Callers must special-case strange types; return None or raise an exception.

Important notes

  • These ideas come together again in module 19 (code quality) and module 20 (building applications).

Key takeaways

  • Small, single-purpose, well-named functions are easiest to maintain.
  • Pure functions are predictable and testable.
  • Keep I/O at the edges and return consistent types.

Try it yourself

  1. 1
    Take a 40-line script you wrote and split it into at least four functions plus main().
  2. 2
    Rewrite a function that prints its result so that it returns it instead, and add assert-based tests.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

15 questions cover the “Functions” module. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this module