๐งฉ What is a function?
A function is a reusable block of code that accepts inputs (arguments) and produces an output (return value). Instead of copy-pasting the same logic 50 times in your loan calculator, you write it once as a function and call it everywhere.
return result
Functions solve two big problems: code duplication (DRY โ Don't Repeat Yourself) and testing. A small reusable piece is easier to test and fix than tangled code scattered across files.
๐ Core function concepts
๐ฆ Real scenario: SouthBank India
SouthBank India processes 2,000+ personal loans monthly. Each loan application copies the same EMI formula (Equated Monthly Installment) โ principal, rate, tenure. This copy-paste code is scattered across their system, hard to test, impossible to maintain. One typo, and 50 places break.
You're hired to extract that logic into a reusable function. Once it's tested once, it works everywhere. That's the power of functions.
โ๏ธ Step-by-step: Extract a function
Step 1: Before โ copy-pasted mess
This is what SouthBank's code looks like. The EMI formula is repeated everywhere:
Step 2: After โ extract a function
Now extract the formula into a single reusable function:
Step 3: Return multiple values
A function can return more than one value as a tuple. SouthBank wants both EMI and total interest paid:
Step 4: Keyword and default arguments
Functions can have default values. If SouthBank usually checks for 5-year loans, make that the default:
Step 5: *args and **kwargs
M-Pesa Kenya's fee calculator needs to handle different fee types for different recipient categories. Use *args for variable positional args and **kwargs for keyword args:
๐ผ Where you'll see functions
Real use in production code
AI connection: Functions in machine learning
Every machine learning model is a function. You feed it input data (features), the model processes it through layers, and returns output (a prediction). Model training is just optimization โ finding the best parameters for that function. When you deploy a model, you're really deploying a function that takes raw data and returns a probability or classification.
model(features) loss_function(predictions, actuals) train()
M-Pesa Kenya charges a fee based on the transfer amount. Write a function calculate_fee(amount) that:
- Returns 0% fee if amount < KSh 100
- Returns 1% fee if amount is KSh 100โ1000
- Returns 0.5% fee if amount > KSh 1000
Test it with 50, 500, and 5000.
Hint: Use if/elif/else. Return amount * (fee_rate / 100).
๐ค Interview questions
It returns None. Every Python function implicitly returns None if it doesn't have a return statement. You can explicitly write return None or just omit it.
Positional arguments are matched by order: func(10, 20) maps to the first and second parameter. Keyword arguments use names: func(rate=10, principal=20). Keywords can be in any order and are clearer in code.
LEGB stands for the scope lookup order in Python: Local (inside the function), Enclosing (outer function if nested), Global (module level), Built-in (Python's built-ins like print()). When you reference a variable, Python searches these scopes in this order and uses the first match.
*args captures positional arguments as a tuple: def func(*args) lets you call func(1, 2, 3) and access them as a tuple. **kwargs captures keyword arguments as a dict: def func(**kwargs) lets you call func(x=1, y=2) and access them as a dictionary.
A pure function returns the same output for the same input and doesn't modify anything outside itself. Example: def double(x): return x * 2. A side-effect function modifies global state, writes to a file, prints, or makes an API call. Pure functions are easier to test and reason about. Banking code usually prefers pure functions for calculations.
๐ฏ Quick quiz
def greet(): print("Hi")calculate_emi(10_00_000, 9.5) and the function has a default tenure_years=5, what happens?๐ Cheatsheet
| Concept | Example | Purpose |
|---|---|---|
| Define function | def calculate_emi(p, r, t): |
Create a reusable block of code |
| Return value | return emi |
Send a result back to the caller |
| Default argument | def calc(p, r, t=5): |
Use a fallback if argument not provided |
| Keyword argument | calc(p=100, r=9.5, t=7) |
Pass arguments by name (any order) |
| Multiple returns | return emi, interest |
Return a tuple of values |
| *args | def func(*args): ... |
Accept variable positional arguments as tuple |
| **kwargs | def func(**kwargs): ... |
Accept variable keyword arguments as dict |
| Lambda | lambda x: x * 2 |
Quick anonymous function (one line) |
| Docstring | """Calculate EMI.""" |
Document what a function does |
| Local scope | Variables inside function | Only exist within that function |
โ ๏ธ Common mistakes
def calculate_emi(p, r, t) | Right: def calculate_emi(p, r, t):def calc(): print(result) | Right: def calc(): return result. Print only shows on screen; return passes data to the caller.def func(x=[]): and then modifying x. Mutable defaults are shared across calls. Use x=None instead and create a new list inside.๐ฏ Key takeaways
- A function is a reusable block of code. Extract repeated logic into functions (DRY principle).
- Define with
def, pass data in as arguments, return results. One function, tested once, used everywhere. - Positional arguments:
func(10, 20). Keyword arguments:func(x=10, y=20). Keywords are clearer. - Default arguments let you call a function without all parameters:
def func(x, y=5): - A function can return multiple values as a tuple:
return emi, interest - Scope matters: variables inside a function are local (LEGB rule). Use return to send data out.
Master Python with Ramayai
Join the Best AI Program: The AI-Era Analyst โ 5 months, fully online, with placement assistance. Week 1 is free.
Explore The AI-Era Analyst โ