๐Ÿงฉ 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.

def function_name(arguments):
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

def
def calculate_emi()
Keyword to define a new function
Arguments
(principal, rate)
Inputs a function receives
Return
return emi
Output the function sends back
Scope
Local vs Global
Where a variable exists
Lambda
lambda x: x * 2
One-line anonymous function
*args / **kwargs
def func(*a, **kw)
Variable arguments

๐Ÿฆ Real scenario: SouthBank India

๐Ÿฆ
India โ€ข Mumbai โ€ข Banking
SouthBank's loan calculator pain

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.

โ‚น10,00,000
Loan Principal
9.5%
Annual Rate
5 years
Tenure

โš™๏ธ 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:

code1: The problem

Step 2: After โ€” extract a function

Now extract the formula into a single reusable function:

code2: The solution

Step 3: Return multiple values

A function can return more than one value as a tuple. SouthBank wants both EMI and total interest paid:

code3: Multiple return values

Step 4: Keyword and default arguments

Functions can have default values. If SouthBank usually checks for 5-year loans, make that the default:

code4: Defaults and keyword arguments

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:

code5: *args and **kwargs

๐Ÿ’ผ Where you'll see functions

Real use in production code

๐Ÿฆ
calculate_emi(), apply_loan_interest(), check_fraud_score()
Banking systems refactor common loan logic into functions so all branches use identical math.
๐Ÿ“ฑ
send_notification(), log_transaction(), validate_phone()
Mobile apps call the same send_notification() for SMS, email, and push โ€” no duplication.
๐Ÿ›’
apply_discount(), calculate_tax(), format_receipt()
E-commerce rewrites discount logic once, then every product page, checkout, and invoice use the same function.
๐Ÿ”
hash_password(), verify_token(), check_permissions()
Security functions are tested once, then trusted everywhere a login or permission check is needed.

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()

Challenge: Write a fee calculator

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

Question 1 of 5
Which keyword defines a function in Python?
Question 2 of 5
What does this function return?
def greet(): print("Hi")
Question 3 of 5
If you call calculate_emi(10_00_000, 9.5) and the function has a default tenure_years=5, what happens?
Question 4 of 5
Which function call uses keyword arguments?
Question 5 of 5
What does a pure function do?
0
/5
Great effort!

๐Ÿ“‹ 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

Forgetting the colon after the function signature
Wrong: def calculate_emi(p, r, t) | Right: def calculate_emi(p, r, t):
Not indenting the function body
The lines inside the function must be indented. Python uses indentation to know where the function ends.
Returning vs printing
Wrong: def calc(): print(result) | Right: def calc(): return result. Print only shows on screen; return passes data to the caller.
Modifying default mutable arguments
Avoid 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.
Africa & India's Best AI Academy
๐Ÿค– AI-first ๐ŸŽ“ Placement Assistance

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 โ†’