Python Tutorial chapters (19)
  1. 01Python Introduction
  2. 02Python Syntax, Keywords & Operators
  3. 03Python Variables & Data Types
  4. 04Python Strings
  5. 05Python Control Statements
  6. 06Python Lists
  7. 07Python Tuples
  8. 08Python Sets
  9. 09Python Dictionaries
  10. 10Python Functions
  11. 11Python Modules
  12. 12Python OOPs
  13. 13Python Exception Handling
  14. 14Python File Handling
  15. 15Python Searching & Sorting
  16. 16Python Advanced Topics
  17. 17Python MySQL
  18. 18Python MongoDB & SQLite
  19. 19Python MCQ

Chapter 10

Python Functions

6 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

A function is a named, reusable block of code.

You will learn defining functions with def, lambda functions, important built-in functions, *args and **kwargs, and recursion.

Functions remove repetition and keep programs organised and testable.

Every library, API handler, data pipeline and script.

1

Python Functions

A function is a named block of statements that performs a task, runs only when called, can accept inputs (parameters) and can give back a result using return.

In short: A function is a recipe with a name. Write it once, then use it whenever you need it.

Call a function → get a result

Think about it

Large programs are only manageable if split into small functions. A calculator app has add(), subtract() and so on, each reused many times.

Types: built-in (len), user-defined (def), anonymous (lambda) and methods (functions on objects).

Parameters are names in the definition; arguments are the actual values in the call.

Argument styles: positional, keyword (f(b=2, a=1)), default (def f(x=10)), variable (*args, **kwargs).

A function without return, or with a bare return, gives None.

Variables assigned inside a function are LOCAL; the LEGB rule (Local, Enclosing, Global, Built-in) decides name lookup, and global or nonlocal lets a function rebind outer names.

Functions are first-class objects: they can be stored in variables, passed as arguments and returned.

Benefits

reuse, readability, easier testing and less duplication.

Key points

  • Parameter: Name listed in the function definition.
  • Argument: Actual value passed in the call.
  • Return value: The result sent back to the caller.
  • Local scope: Names that exist only inside the function.

Example

Code
Defining and calling functions:
def greet(name):
    print("Hello,", name)

greet("Ann")                 # Hello, Ann

def add(a, b):
    return a + b

total = add(3, 4)
print(total)                 # 7

def power(base, exp=2):      # default parameter
    return base ** exp

print(power(5), power(2, 3), power(exp=3, base=2))   # 25 8 8

def stats(nums):
    return min(nums), max(nums), sum(nums) / len(nums)

lo, hi, avg = stats([2, 4, 6])
print(lo, hi, avg)           # 2 6 4.0

def no_return():
    x = 5

print(no_return())           # None

count = 0
def inc():
    global count             # modify the global variable
    count += 1
inc(); inc()
print(count)                 # 2

def apply(f, v):             # functions are objects
    return f(v)
print(apply(abs, -9))        # 9
2

def Function in Python

The def keyword defines a user-defined function: def name(parameters): followed by an indented body. Optional parts are a docstring, return statements and type hints.

In short: def tells Python "here comes a new function with this name and these inputs".

Think about it

The mutable default and pass-by-reference behaviour are classic interview traps. def calculate_tax(amount, rate=0.18) is called from many parts of a billing system.

Syntax

`def function_name(p1, p2=default):` + indented block.

def is an executable statement: the function object is created when the line runs, so a function must be defined before it is called.

The first string in the body is a docstring, readable via help(f) or `f.

__doc__`.

Use pass for an empty body.

DEFAULT values are evaluated ONCE when the function is defined, so a mutable default like def f(x, items=[]) is shared between calls; use None and create the list inside.

Rules for order: non-default parameters first, then defaults; keyword arguments come after positional ones in a call.

A function can return several values (a tuple) and can contain other functions (nested/closure).

Type hints (def f(x: int) -> int) document intent but are not enforced.

Arguments are passed by object reference: mutating a passed list changes the caller list, but rebinding the parameter does not.

Key points

  • Docstring: String literal at the start of a function describing it.
  • Keyword argument: Argument passed with name=value in the call.
  • Type hint: Annotation such as x: int; informational only.
  • Closure: Inner function that remembers variables of the outer function.

Example

Code
def syntax, docstring, defaults and traps:
def area(length, width=1):
    """Return the area of a rectangle."""
    return length * width

print(area(4, 5), area(4))      # 20 4
print(area.__doc__)             # Return the area of a rectangle.

# mutable default trap
def bad(x, items=[]):
    items.append(x)
    return items
print(bad(1), bad(2))           # [1, 2] [1, 2]   (shared list!)

def good(x, items=None):
    if items is None:
        items = []
    items.append(x)
    return items
print(good(1), good(2))         # [1] [2]

def change(lst):
    lst.append(99)              # mutates caller list
    lst = [0]                   # rebinding has no effect outside
nums = [1]
change(nums)
print(nums)                     # [1, 99]

def make_multiplier(n):         # closure
    def multiply(x):
        return x * n
    return multiply
triple = make_multiplier(3)
print(triple(5))                # 15

def typed(a: int, b: int = 2) -> int:
    return a + b
print(typed(3))                 # 5

def todo():
    pass                        # empty body placeholder
3

Python Lambda Functions

A lambda is a small anonymous function written as a single expression: `lambda arguments: expression`. It returns the value of the expression automatically.

In short: A lambda is a one-line throwaway function without a name.

Think about it

Sorting by a custom key and using map/filter appear in many exam and interview questions. Sorting a list of students by marks: sorted(students, key=lambda s: s["marks"]).

A lambda can take any number of arguments but only ONE expression, no statements such as assignment or return.

square = lambda x: x * x is the same as a def but is not recommended for named functions (use def).

The main use is as a short argument to higher-order functions: sorted(data, key=lambda p: p[1]), `max(...

, key=...

), map(lambda x: x * 2, nums) and filter(lambda x: x > 0, nums)`.

map and filter return lazy iterators, so wrap with list().

A conditional expression can be used inside: lambda x: "even" if x % 2 == 0 else "odd".

Lambdas capture variables by reference, so lambdas created in a loop all see the final value unless you bind it with a default lambda i=i: i.

For reducing a list use `functools.

reduce`.

Key points

  • Anonymous function: Function with no name.
  • Higher-order function: Function that takes or returns another function.
  • map / filter: Apply a function to every item, or keep items where it is True.

Example

Code
Lambda with map, filter, sorted and reduce:
square = lambda x: x * x
add = lambda a, b: a + b
print(square(5), add(2, 3))              # 25 5

nums = [1, 2, 3, 4, 5, 6]
print(list(map(lambda x: x * 2, nums)))        # [2, 4, 6, 8, 10, 12]
print(list(filter(lambda x: x % 2 == 0, nums)))# [2, 4, 6]

people = [("Ann", 25), ("Raj", 20), ("Li", 30)]
print(sorted(people, key=lambda p: p[1]))
# [('Raj', 20), ('Ann', 25), ('Li', 30)]
print(max(people, key=lambda p: p[1]))         # ('Li', 30)

parity = lambda n: "even" if n % 2 == 0 else "odd"
print(parity(7))                         # odd

from functools import reduce
print(reduce(lambda a, b: a * b, [1, 2, 3, 4]))   # 24

funcs = [lambda i=i: i for i in range(3)]  # bind i with a default
print([f() for f in funcs])              # [0, 1, 2]
4

Python Built-in Functions

Built-in functions are functions always available in Python without importing anything, such as print, len, type, range, sum, min, max, sorted, enumerate, zip and input.

In short: These are Python tools already in your toolbox. Just call them.

Ready-made tools already in Python

Think about it

Using built-ins gives shorter, faster and more readable programs. sum(prices) / len(prices) gives an average in one line.

Input/output: print, input (always returns a string).

Type and conversion: int, float, str, bool, list, tuple, set, dict, type, `isinstance`.

Numbers: abs, round (round(2.5) is 2 because ties go to the even number), pow, divmod, sum, min, max.

Sequences: len, sorted, reversed, `enumerate, zip, range`.

Functional: map, filter, any (True if at least one item is truthy), all (True if every item is truthy; True for empty).

Objects: dir, help, id, hasattr, getattr.

ord and chr convert between characters and codes.

reversed, map, filter, zip and `enumerate` return iterators.

List all built-ins with dir(__builtins__).

Do not name your variables list, sum or max, because that hides the built-in.

Key points

  • Built-in: Available without import.
  • Iterator: Object that gives items one at a time.
  • Shadowing: Reusing a built-in name for a variable, which hides the built-in.

Example

Code
Frequently used built-in functions:
nums = [4, 9, 1, 7]
print(len(nums), sum(nums), min(nums), max(nums))   # 4 21 1 9
print(sorted(nums), sorted(nums, reverse=True))     # [1, 4, 7, 9] [9, 7, 4, 1]
print(list(reversed(nums)))                         # [7, 1, 9, 4]

print(abs(-7), round(3.14159, 2), pow(2, 5))        # 7 3.14 32
print(round(2.5), round(3.5))                       # 2 4   (ties to even)
print(divmod(17, 5))                                # (3, 2)

for i, v in enumerate(["a", "b"], start=1):
    print(i, v)                                     # 1 a / 2 b
print(list(zip([1, 2, 3], "xy")))                   # [(1, 'x'), (2, 'y')]

print(any([0, "", 3]), all([1, 2, 0]), all([]))     # True False True

print(type(5), isinstance(5, int), isinstance("a", (int, str)))
print(int("42") + 1, float("2.5"), str(10) + "0", bool([]))   # 43 2.5 100 False
print(ord("A"), chr(98))                            # 65 b

name = input("Name: ")      # always a string
age = int(input("Age: "))   # convert when you need a number

# avoid shadowing:
# sum = 5   -> sum([1, 2]) would now fail
5

*args and **kwargs in Python

*args collects any number of extra positional arguments into a tuple, and **kwargs collects any number of extra keyword arguments into a dictionary. The names args and kwargs are only conventions; the stars are what matter.

In short: *args = "give me any number of plain values". **kwargs = "give me any number of name=value pairs".

Think about it

They appear in decorators, frameworks and every interview on Python functions. A logging helper that accepts any number of values and options: log("x", "y", level="INFO").

Parameter order must be: normal parameters, *args, keyword-only parameters, **kwargs: def f(a, b=1, *args, c, **kwargs).

Inside the function args is a tuple and kwargs is a dict.

At the CALL site the stars UNPACK: f(*[1, 2, 3]) spreads a list as positional arguments, f(**{"a": 1}) spreads a dict as keyword arguments.

Use them to write flexible functions (like print, which accepts any number of values), to forward arguments to another function (wrappers and decorators), and to extend base-class constructors.

A bare * in the parameter list makes later parameters keyword-only.

Passing the same argument both positionally and by keyword raises TypeError.

Key points

Example

Code
*args and **kwargs:
def total(*args):
    print(args)                  # (1, 2, 3)
    return sum(args)
print(total(1, 2, 3))            # 6
print(total())                   # 0

def profile(**kwargs):
    print(kwargs)                # {'name': 'Ann', 'age': 20}
    for k, v in kwargs.items():
        print(k, "=", v)
profile(name="Ann", age=20)

def mix(a, b=10, *args, flag=False, **kwargs):
    print(a, b, args, flag, kwargs)
mix(1, 2, 3, 4, flag=True, x=9)  # 1 2 (3, 4) True {'x': 9}

def add3(x, y, z):
    return x + y + z
nums = [1, 2, 3]
print(add3(*nums))               # 6   (unpack list)
info = {"x": 1, "y": 2, "z": 3}
print(add3(**info))              # 6   (unpack dict)

def logger(func):
    def wrapper(*args, **kwargs):    # forward everything
        print("calling", func.__name__)
        return func(*args, **kwargs)
    return wrapper

@logger
def hello(name, punct="!"):
    return "Hi " + name + punct
print(hello("Li", punct="?"))    # prints calling hello, then Hi Li?

def only_kw(*, a, b):            # keyword-only
    return a + b
print(only_kw(a=1, b=2))         # 3
6

Recursion in Python

Recursion is a technique where a function calls itself to solve a smaller version of the same problem. Every recursive function needs a BASE CASE that stops the calls and a RECURSIVE CASE that moves toward it.

In short: Solve a big problem by solving a slightly smaller copy of it, until it is so small the answer is obvious.

Recursion call stack: each call waits for the next to return
Recursion call stack: each call waits for the next to return

Think about it

Recursion is a core exam and interview topic and the basis of tree and graph algorithms. Walking through folders inside folders, where each folder is processed the same way.

Example

factorial(n) = n * factorial(n-1) with base case factorial(0) = 1.

Each call is placed on the call stack and removed as it returns.

Without a base case, or without progress toward it, Python raises RecursionError when the depth passes the limit (default about 1000; see `sys.

getrecursionlimit()`).

Naive Fibonacci repeats work exponentially; memoization with `functools.

lru_cache` stores results and makes it linear.

Recursion suits trees, nested data, divide-and-conquer (binary search, merge sort) and backtracking.

An iterative loop is usually faster and uses less memory in Python because there is no tail-call optimisation.

Steps for writing: (1) write the base case, (2) trust the function for n-1, (3) combine.

Key points

  • Base case: Condition that ends the recursion.
  • Recursive case: Call to itself with a smaller input.
  • Call stack: Memory structure holding active function calls.
  • Memoization: Caching results to avoid repeated work.

Example

Code
Recursion: base case, recursive case, memoization:
def factorial(n):
    if n == 0:                   # base case
        return 1
    return n * factorial(n - 1)  # recursive case
print(factorial(5))              # 120

def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)
print([fib(i) for i in range(8)])   # [0, 1, 1, 2, 3, 5, 8, 13]

def sum_digits(n):
    if n < 10:
        return n
    return n % 10 + sum_digits(n // 10)
print(sum_digits(1234))          # 10

def reverse(s):
    if len(s) <= 1:
        return s
    return reverse(s[1:]) + s[0]
print(reverse("python"))         # nohtyp

def countdown(n):
    if n == 0:
        print("Go!")
        return
    print(n)
    countdown(n - 1)
countdown(3)                     # 3 2 1 Go!

import sys
print(sys.getrecursionlimit())   # 1000 by default

def forever(n):                  # no base case
    return forever(n + 1)
try:
    forever(0)
except RecursionError:
    print("too deep")

from functools import lru_cache
@lru_cache(maxsize=None)
def fast_fib(n):
    return n if n < 2 else fast_fib(n - 1) + fast_fib(n - 2)
print(fast_fib(60))              # 1548008755920

Solved examples

Example 01 · Basic

Write a function that returns the largest of three numbers without using max().

Given Data:
    Required To Find:

    Function

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: Take a, b, c
    Step 2: Compare using and
    Step 3: Return the biggest
    Final Answer: def biggest(a, b, c): if a >= b and a >= c: return a if b >= c: return b return c

    Approach note: Test with equal values as well.

    Example 02 · Basic

    Write a function using *args that returns the average of any number of values.

    Given Data:
      Required To Find:

      Function

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: Collect values in args
      Step 2: Guard against empty input
      Step 3: Return sum(args)/len(args)
      Final Answer: def avg(*args): return sum(args) / len(args) if args else 0

      Approach note: args is a tuple, so len() and sum() work directly.

      Example 03 · Intermediate

      Write a recursive function for the power x ** n (n >= 0).

      Given Data:
        Required To Find:

        Recursive function

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: Base: n == 0 returns 1
        Step 2: Recursive: x * power(x, n - 1)
        Final Answer: def power(x, n): if n == 0: return 1 return x * power(x, n - 1)

        Approach note: Use n // 2 splitting for O(log n) speed.

        Example 04 · Basic

        Sort words = ["pear", "fig", "banana"] by length using a lambda.

        Given Data:
          Required To Find:

          Sorted list

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: key=lambda w: len(w)
          Step 2: Shortest first
          Final Answer: sorted(words, key=lambda w: len(w)) → ['fig', 'pear', 'banana']

          Approach note: key=len gives the same result.

          Real-world applications

          Python

          Using Python Functions in real projects

          Every library, API handler, data pipeline and script.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: A function without return gives nothing.

          Why this is wrong: It returns None.

          ✅ Verified Truth: print(f()) shows None.

          ⚠️ Exam Tip: Common output question.

          ❌ Myth: Default list arguments are fresh on every call.

          Why this is wrong: Defaults are evaluated once at definition time.

          ✅ Verified Truth: Use None as the default and create the list inside.

          ⚠️ Exam Tip: Classic interview trap.

          ❌ Myth: Recursion has no limit.

          Why this is wrong: The call stack is finite.

          ✅ Verified Truth: Python stops with RecursionError near depth 1000.

          ⚠️ Exam Tip: Mention base case and memoization.

          Revision notes

          A function is a named, reusable block of code. You will learn defining functions with def, lambda functions, important built-in functions, *args and **kwargs, and recursion.

          High-Yield Quick Revision Points

          1. def name(params): body; return gives the result, default None
          2. Default values are evaluated once; avoid mutable defaults
          3. lambda args: expression (single expression only)
          4. any/all, enumerate, zip, sorted, map, filter are built-in
          5. *args = tuple, **kwargs = dict; star at call site unpacks
          6. Recursion needs a base case; limit about 1000; use lru_cache

          Practice questions

          Question 1 · MCQ (Interview / semester)

          What does a function without a return statement return?

          Question 2 · MCQ (Interview / semester)

          Inside a function, *args is a:

          Question 3 · MCQ (Interview / semester)

          Inside a function, **kwargs is a:

          Question 4 · MCQ (Interview / semester)

          Value of (lambda x, y: x + y)(2, 3)?

          Question 5 · MCQ (Interview / semester)

          What error is raised when recursion has no base case?

          Question 6 · MCQ (Interview / semester)

          What does round(2.5) return in Python 3?