Tutorials Python Python Functions
Ch 23 / 58
Python Intermediate 13 min read Chapter 23 of 58

Python Functions

Functions are the fundamental building blocks of clean, reusable Python code. A function groups a set of statements under a name, lets you pass data in through parameters, and return results through return values. This chapter covers everything: defining and calling functions with an anatomy diagram, positional and keyword arguments, default values, the flexible *args and **kwargs, type hints, variable scope, docstrings, and practical real-world patterns every Python developer must know.

What you'll learn in this chapter
Defining and calling functions — def syntax
Parameters: positional, keyword and defaults
Return values — single, multiple and None
*args and **kwargs — flexible functions
Variable scope: local, global and nonlocal
Docstrings, type hints and real-world patterns
Advertisement

Defining & Calling Functions

A function is defined with the def keyword, followed by the function name, parentheses containing zero or more parameters, and a colon. The indented block is the function body. A function does nothing until it is called by name with parentheses.

Anatomy of a Python Function
def greet(name: str, greeting: str = "Hello") -> str: """Return a personalised greeting string.""" message = f"{greeting}, {name}!" return message
def — keyword that starts a function
function name (snake_case convention)
parameters — local variables inside the function
default value — used when argument is omitted
docstring — describes what the function does
return statement — sends value back to caller
Python — functions_basics.py
# Simplest function — no params, no return
def greet():
    print("Hello, World!")

greet()              # Hello, World!
greet()              # can call many times

# Function with a parameter
def greet_user(name):
    print(f"Hello, {name}!")

greet_user("Alice")  # Hello, Alice!
greet_user("Bob")    # Hello, Bob!

# Functions are first-class objects — assign to variable
say_hi = greet
say_hi()             # Hello, World!

# Check function type
print(type(greet))   # <class 'function'>

# Docstring — first statement describes the function
def add(a, b):
    """Return the sum of a and b."""
    return a + b

print(add.__doc__)    # Return the sum of a and b.
print(add(3, 4))     # 7
def vs calling Writing def greet(): only defines the function — it does not run it. The function runs only when you call it: greet(). You can define once and call as many times as needed.

Parameters & Arguments

A parameter is the variable in the function definition; an argument is the actual value you pass when calling the function. Python supports positional arguments, keyword arguments, and default parameter values — each serving a different purpose.

Python — function_parameters.py
# Positional arguments — order matters
def power(base, exponent):
    return base ** exponent

print(power(2, 10))    # 1024  — base=2, exponent=10
print(power(10, 2))    # 100   — swapped!

# Keyword arguments — order doesn't matter
print(power(exponent=10, base=2))  # 1024 — explicit names

# Default parameter values
def greet(name, greeting="Hello", punct="!"):
    return f"{greeting}, {name}{punct}"

print(greet("Alice"))                     # Hello, Alice!
print(greet("Bob", "Hi"))                  # Hi, Bob!
print(greet("Carol", greeting="Hey"))     # Hey, Carol!
print(greet("Dave", punct="."))           # Hello, Dave.

# ⚠️ Mutable default argument trap!
def bad_append(item, lst=[]):   # default list is shared!
    lst.append(item)
    return lst

print(bad_append(1))   # [1]
print(bad_append(2))   # [1, 2]  ← bug! list accumulates!

# ✅ Fix: use None as default
def safe_append(item, lst=None):
    if lst is None:
        lst = []
    lst.append(item)
    return lst
positional args
Matched left-to-right by position. Order is critical — swapping args changes the call.
keyword args
Passed by name. Order doesn't matter and they make call sites more readable: power(base=2, exponent=10).
default values
Set in the function definition. Must come after non-default parameters. Never use mutable objects (list, dict) as defaults.

Return Values

The return statement sends a value back to the caller and exits the function immediately. A function without return (or with bare return) returns None. You can return multiple values as a tuple using comma separation.

Python — return_values.py
# Single return value
def square(n):
    return n ** 2

print(square(5))    # 25

# No return — returns None implicitly
def say_hello():
    print("Hello")

result = say_hello()
print(result)         # None

# Multiple return values — returned as tuple
def min_max(numbers):
    return min(numbers), max(numbers)

lo, hi = min_max([5, 1, 9, 3])
print(lo, hi)         # 1 9

# Early return — guard clause pattern
def divide(a, b):
    if b == 0:
        return None    # early exit
    return a / b

print(divide(10, 2))  # 5.0
print(divide(10, 0))  # None  — no ZeroDivisionError

# Return different types based on logic
def classify(n):
    if n > 0: return "positive"
    if n < 0: return "negative"
    return "zero"

print(classify(5))   # positive
print(classify(-3))  # negative
print(classify(0))   # zero
Advertisement
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Django & DRF FastAPI PostgreSQL Machine Learning Docker & AWS Real Projects AI Tools

*args and **kwargs — Flexible Functions

*args lets a function accept any number of positional arguments — they are collected into a tuple. **kwargs collects any number of keyword arguments into a dictionary. Together, they create maximally flexible APIs.

Python — args_kwargs.py
# *args — variable positional arguments (tuple)
def total(*numbers):
    print(type(numbers))       # <class 'tuple'>
    return sum(numbers)

print(total(1, 2, 3))        # 6
print(total(10, 20, 30, 40)) # 100
print(total())                # 0 — empty tuple

# **kwargs — variable keyword arguments (dict)
def build_profile(**info):
    print(type(info))          # <class 'dict'>
    for key, val in info.items():
        print(f"  {key}: {val}")

build_profile(name="Alice", age=25, city="Vadodara")
# name: Alice  age: 25  city: Vadodara

# Combined — positional + *args + keyword + **kwargs
def logger(level, *messages, sep="\n", **meta):
    print(f"[{level.upper()}]")
    print(sep.join(messages))
    if meta:
        print("Meta:", meta)

logger("info", "Server started", "Port: 8080", user="admin")

# Unpack list/dict when calling a function
nums   = [1, 2, 3]
params = {"name": "Bob", "age": 30}

print(total(*nums))            # unpack list → positional args
build_profile(**params)        # unpack dict → keyword args
Syntax Inside function Accepts Type
def f(*args) args Any number of positional args tuple
def f(**kwargs) kwargs Any number of keyword args dict
f(*my_list) — Unpack list/tuple as positional —
f(**my_dict) — Unpack dict as keyword args —

Variable Scope — Local, Global & Nonlocal

Scope determines where a variable is visible. Variables created inside a function are local — invisible outside it. Variables created at the module level are global. Python looks up names using the LEGB rule: Local → Enclosing → Global → Built-in.

Global Scope (module level)
x = 10 ← accessible everywhere below
Local Scope (inside function)
y = 20 ← only visible here
x = 10 ← can READ global x (without global keyword)
⚠ x = 99 → creates NEW local x, doesn't change global
Python — variable_scope.py
# Local scope — variable only exists inside function
def my_func():
    local_var = "I'm local"
    print(local_var)

my_func()              # I'm local
# print(local_var)  →  NameError: not defined

# Reading a global variable — allowed without keyword
count = 0

def show_count():
    print(count)       # can READ global count

show_count()           # 0

# Modifying global variable — needs global keyword
def increment():
    global count       # declare intent to modify global
    count += 1

increment()
increment()
print(count)           # 2

# nonlocal — modify variable in enclosing function
def outer():
    x = 10
    def inner():
        nonlocal x     # refers to outer's x
        x += 5
    inner()
    print(x)           # 15

outer()
Avoid global — prefer passing arguments Using global is a code smell. Functions that read and modify global state are hard to test and debug. Pass data in through parameters and out through return values instead.

Type Hints & Docstrings

Type hints (Python 3.5+) annotate parameter types and return types. They don't change runtime behaviour — Python still runs without type checking — but they dramatically improve IDE auto-complete, code readability, and help tools like mypy catch bugs. Docstrings describe what a function does, its arguments and return value.

Python — type_hints_docstrings.py
# Type hints — parameter: type and -> return type
def add(a: int, b: int) -> int:
    return a + b

def greeting(name: str) -> str:
    return f"Hello, {name}"

# Optional and union types (Python 3.10+)
from typing import Optional, List, Dict, Union

def find_user(user_id: int) -> Optional[str]:
    """Return username or None if not found."""
    users = {1: "Alice", 2: "Bob"}
    return users.get(user_id)

def process(data: List[int]) -> Dict[str, int]:
    """
    Process a list of integers.

    Args:
        data: list of integers to process

    Returns:
        dict with 'min', 'max', 'sum' keys
    """
    return {"min": min(data), "max": max(data), "sum": sum(data)}

print(process([1, 5, 3]))  # {'min': 1, 'max': 5, 'sum': 9}

# Python 3.10+ union syntax: int | None (no Union needed)
def parse_int(s: str) -> int | None:
    try:
        return int(s)
    except ValueError:
        return None

Real-World Patterns

Here are the most important professional patterns with Python functions — patterns you'll use in every real project:

Python — real_world_functions.py
# ── 1. Guard clause — early return for clean logic ──
def process_order(order):
    if not order:
        return "No order provided"
    if order["quantity"] <= 0:
        return "Invalid quantity"
    # happy path — no deep nesting
    return f"Processing {order['quantity']} × {order['item']}"

print(process_order({"item": "laptop", "quantity": 2}))

# ── 2. Pure function — no side effects ──────────────
def celsius_to_fahrenheit(c: float) -> float:
    return (c * 9 / 5) + 32

print(celsius_to_fahrenheit(100))  # 212.0

# ── 3. Builder / factory function ──────────────────
def create_user(name: str, role: str = "viewer") -> dict:
    return {"name": name, "role": role, "active": True}

alice = create_user("Alice", role="admin")
bob   = create_user("Bob")

# ── 4. Functions as arguments ─────────────────────
def apply(func, value):
    return func(value)

print(apply(str.upper, "hello"))  # HELLO
print(apply(len, [1, 2, 3]))       # 3

numbers = [3, 1, 4, 1, 5]
print(sorted(numbers, key=lambda x: -x))  # [5,4,3,1,1]

# ── 5. Memoisation with dict cache ────────────────
_cache = {}

def fibonacci(n: int) -> int:
    if n <= 1: return n
    if n in _cache: return _cache[n]
    _cache[n] = fibonacci(n-1) + fibonacci(n-2)
    return _cache[n]

print(fibonacci(30))   # 832040 — fast with cache

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice all function examples from this chapter directly in your browser with these free Python environments.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Test every function example instantly.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • Define functions with def name(params):. The body executes only when the function is called.
  • Positional arguments are matched by order; keyword arguments are matched by name. Default values make parameters optional.
  • Never use mutable objects (lists, dicts) as default parameter values — use None and create inside the function.
  • return sends a value to the caller and exits the function. Without return, the function returns None. Multiple values are returned as a tuple.
  • *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict.
  • Use *my_list and **my_dict at call sites to unpack sequences/dicts into arguments.
  • Variable scope: local variables only exist inside their function. Use global to modify a global variable; use nonlocal to modify an enclosing function's variable.
  • Type hints (def f(a: int) -> str:) improve readability and IDE support. Docstrings document purpose, args, and return value.
  • Key patterns: guard clauses for early returns, pure functions without side effects, functions as arguments for higher-order programming.
⚡
Free Resource
Download our Python Functions Cheat Sheet
def syntax, parameters, return, *args/**kwargs, scope & type hints — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

A parameter is the variable name defined in the function signature. An argument is the actual value passed when calling the function. They are two names for the same concept — one at definition, one at call site.

def greet(name):   # ← "name" is a PARAMETER
    print(name)

greet("Alice")     # ← "Alice" is an ARGUMENT
✓ Answer

Default values in Python are evaluated once when the function is defined — not each time it's called. If the default is a mutable object (list, dict), all calls share the same object. Mutating it in one call affects all subsequent calls, causing subtle bugs.

# ❌ Shared default list — bug!
def bad(item, lst=[]):
    lst.append(item); return lst

print(bad(1))   # [1]
print(bad(2))   # [1, 2]  ← unexpected!

# ✅ Fix: use None
def good(item, lst=None):
    if lst is None: lst = []
    lst.append(item); return lst
✓ Answer

*args collects any extra positional arguments into a tuple — useful when you don't know how many positional values will be passed.

**kwargs collects any extra keyword arguments into a dict — useful when you want named options without pre-declaring them.

def f(*args, **kwargs):
    print(args)    # tuple of positionals
    print(kwargs)  # dict of keywords

f(1, 2, x=3, y=4)
# (1, 2)   {'x': 3, 'y': 4}
✓ Answer

A function that has no return statement, or a bare return with no value, implicitly returns None. This is a common source of bugs when developers forget to return a value and then try to use the result:

def greet(name):
    print(f"Hello, {name}")   # no return

result = greet("Alice")
print(result)   # None
✓ Answer

When Python looks up a name, it searches four scopes in order:

  • L — Local: inside the current function
  • E — Enclosing: inside any enclosing function (for nested functions)
  • G — Global: at the module level (top of the file)
  • B — Built-in: Python's built-in names (print, len, etc.)

Python stops at the first scope where it finds the name. If not found anywhere, a NameError is raised.

MCQ 1 of 3
What type does *args collect extra positional arguments into?
MCQ 2 of 3
What does a function with no return statement implicitly return?
MCQ 3 of 3
To modify a global variable inside a function, you must use:

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel