Skip to main content
Albero Academy

Python Functions

Define and call functions, pass arguments, set defaults, use *args/**kwargs, write lambdas, and structure clean reusable code.

Chapter 10Python18 min readBeginner friendly
  • #Python
  • #Functions
  • #Reusable Code

Functions are the smallest reusable unit in Python. Naming them well, choosing the right argument style, and writing useful docstrings are skills that pay off across every project.

Defining functions

Python
def greet(name):
return f"Hello, {name}!"
print(greet("Aanya")) # Hello, Aanya!
# A function with no return — implicitly returns None
def log(message):
print(f"[LOG] {message}")
result = log("starting")
print(result) # None

Arguments — positional, keyword, default

Python
def gst(amount, rate=0.18, label="GST"):
return f"{label}: ₹{amount * rate:.2f}"
# Positional
print(gst(1000)) # GST: ₹180.00
# Override one keyword arg
print(gst(1000, rate=0.05)) # GST: ₹50.00
# Mix positional and keyword
print(gst(1000, label="Service Tax")) # Service Tax: ₹180.00
# All by name (recommended for readability)
print(gst(amount=1000, rate=0.12, label="Sales Tax"))

*args and **kwargs

Python
# *args collects extra positional arguments into a tuple
def total(*nums):
return sum(nums)
print(total(1, 2, 3)) # 6
print(total(1, 2, 3, 4, 5)) # 15
# **kwargs collects extra keyword arguments into a dict
def log(**fields):
for key, value in fields.items():
print(f"{key}: {value}")
log(user="Aanya", action="login", ip="10.0.0.1")
# Combine all four kinds — positional, *args, keyword, **kwargs
def event(name, *participants, level="info", **metadata):
print(name, participants, level, metadata)
event("birthday", "Aanya", "Karan", level="warn", venue="Noida", year=2026)

Return values

Python
# Return multiple values — implicitly a tuple
def split_full_name(full):
first, *rest = full.split()
return first, " ".join(rest)
first, last = split_full_name("Aanya Kapoor Sharma")
print(first, "|", last) # Aanya | Kapoor Sharma
# Early returns make code cleaner
def discount(price, customer):
if customer.is_vip:
return price * 0.7
if customer.age >= 60:
return price * 0.85
return price

Scope & closures

Python uses LEGB lookup — Local, Enclosing, Global, Built-in.

Python
x = 10 # global
def outer():
x = 20 # enclosing
def inner():
x = 30 # local
print("inner:", x)
inner()
print("outer:", x)
outer()
print("global:", x)
# inner: 30
# outer: 20
# global: 10
# Closure: inner function "remembers" enclosing scope
def make_counter():
count = 0
def increment():
nonlocal count # without this, you'd get an UnboundLocalError
count += 1
return count
return increment
c = make_counter()
print(c(), c(), c()) # 1 2 3

Lambda functions

Anonymous, single-expression functions. Best for short, throwaway transforms passed to higher-order functions.

Python
square = lambda x: x * x
print(square(5)) # 25
# Sort a list of dicts by a field
people = [
{"name": "Aanya", "age": 28},
{"name": "Karan", "age": 22},
{"name": "Meera", "age": 35}
]
people.sort(key=lambda p: p["age"])
# filter + map
nums = [1, 2, 3, 4, 5, 6]
evens_squared = list(map(lambda n: n * n, filter(lambda n: n % 2 == 0, nums)))
# [4, 16, 36]
# But comprehensions usually read better
evens_squared = [n * n for n in nums if n % 2 == 0]

Docstrings & type hints

Python
def calculate_emi(
principal: float,
annual_rate: float,
months: int
) -> float:
"""
Calculate the equated monthly instalment.
Args:
principal: loan amount in INR
annual_rate: yearly interest rate as a decimal (0.10 = 10%)
months: tenure in months
Returns:
Monthly instalment in INR.
"""
monthly_rate = annual_rate / 12
num = principal * monthly_rate * (1 + monthly_rate) ** months
den = (1 + monthly_rate) ** months - 1
return num / den
print(round(calculate_emi(500_000, 0.09, 36), 2))
# 15899.85

Key takeaways

  1. 01Use keyword arguments at call sites — readability beats brevity.
  2. 02Never use a mutable default; use None and create the value inside the function.
  3. 03*args collects extra positional args (tuple); **kwargs collects extra keyword args (dict).
  4. 04Closures let inner functions remember enclosing scope — use nonlocal to mutate it.
  5. 05Lambdas are for short, throwaway transforms. Reach for comprehensions or named functions otherwise.
  6. 06Always write a one-line docstring; add type hints — your editor and reviewer will thank you.