Unit 3 of 4 · M.Sc IT Sem 1

Unit 3: Functions, modules and exception handling

Fundamentals of Computer and Programming in Python notes · PTU syllabus (PGCA1902)

5 min read9 topics10 exam questions
On this page
  1. Unit summary
  2. Built-in and user-defined functions
  3. Anonymous functions and scope
  4. Pass by value vs pass by reference
  5. Recursion
  6. Scope and lifetime of variables
  7. Creating and importing modules
  8. Standard modules and packages
  9. Built-in exceptions and handling
  10. User-defined exceptions
  11. Key terms
  12. Quick revision
  13. Important questions

Unit summary

Functions and modules organise code for reuse, and exceptions keep programs from crashing. This unit covers built-in and user-defined functions, anonymous functions, passing arguments, recursion, scope and lifetime of variables, creating and importing modules, standard modules and packages, and built-in and user-defined exceptions.

After this unit you can

  • Define functions with different kinds of arguments and use lambda
  • Write recursive functions and explain scope
  • Create and import modules and packages
  • Handle built-in and user-defined exceptions

PTU syllabus topics

  • Built-in and user-defined functions
  • anonymous functions
  • pass by value vs reference
  • recursion
  • scope and lifetime of variables
  • module creation and importing
  • standard modules and packages
  • built-in and user-defined exceptions
1

Topic 1

Built-in and user-defined functions

  • Built-in functions are always available: print, input, len, type, range, sum, max, min, sorted, abs, round, int, str, list, map, filter, zip, enumerate, open, help.
pythondef area(length, breadth=1):            # default argument
    """Return the area of a rectangle."""  # docstring
    return length * breadth

print(area(5, 4), area(5))              # positional
print(area(breadth=3, length=2))        # keyword arguments

def total(*marks, **info):              # variable-length arguments
    print(info.get("name"), sum(marks))
total(78, 85, 90, name="Riya")

Example

Writing a function: def grade(m): return "Pass" if m >= 40 else "Fail" — grade(55) returns "Pass". Built-ins like max([4, 9, 2]) return 9 and sum(range(1, 11)) returns 55.

Exam tip

A function without a return statement returns None.

2

Topic 2

Anonymous functions and scope

A lambda is a small anonymous function written in one expression: lambda arguments: expression. It is often used with map, filter and sorted.

pythondef area(l, b=1):            # default parameter
    return l * b
print(area(5), area(5, 4))   # 5 20

square = lambda x: x * x     # anonymous function
print(square(6))             # 36

count = 0                    # global
def increment():
    global count             # needed to change a global
    count += 1
  • Scope: a variable created inside a function is local and exists only during the call; variables at the top level are global.
  • assert checks a condition while debugging: assert marks >= 0, "Marks cannot be negative".
  • Command-line arguments: import sys; print(sys.argv) — sys.argv[0] is the script name.
  • Modules: a .py file of functions; use import mymodule or from mymodule import area.

Example

Lambda with sorted: students = [("Asha", 82), ("Ravi", 75)]; sorted(students, key=lambda s: s[1]) sorts by marks, giving [('Ravi', 75), ('Asha', 82)]. list(map(lambda x: x * x, [1, 2, 3])) gives [1, 4, 9].

Exam tip

A lambda can contain only one expression — no statements.

3

Topic 3

Pass by value vs pass by reference

  • Python passes object references ("pass by assignment"). Rebinding a parameter inside a function does not affect the caller; but mutating a mutable object (list, dict) is visible outside.
pythondef change(n, lst):
    n = n + 10          # rebinding: caller's int unchanged (immutable)
    lst.append(4)       # mutation: caller's list changes
x, nums = 5, [1, 2, 3]
change(x, nums)
print(x, nums)          # 5 [1, 2, 3, 4]

Example

Mutable vs immutable arguments: def add_item(lst): lst.append(4) changes the caller's list [1, 2, 3] to [1, 2, 3, 4]. But def change(n): n = 10 does not change the caller's integer, because the name n is simply rebound inside the function.

Exam tip

Changes to mutable objects (lists, dicts) are visible outside; rebinding a parameter is not.

4

Topic 4

Recursion

A recursive function calls itself on a smaller problem and must have a base case. Python limits recursion depth (about 1,000 calls by default) to prevent stack overflow.

pythondef factorial(n):
    return 1 if n <= 1 else n * factorial(n - 1)

def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(factorial(5), [fib(i) for i in range(8)])   # 120 [0, 1, 1, 2, 3, 5, 8, 13]
  • Every recursive function needs a base case; Python's default recursion limit is about 1000 calls (sys.getrecursionlimit()).

Example

Tracing factorial(4): 4 × factorial(3) → 4 × 3 × factorial(2) → 4 × 3 × 2 × factorial(1) → 4 × 3 × 2 × 1 = 24. For fib(5) the recursive calls give 5, but many values are recomputed — memoisation fixes that.

Exam tip

Recursion without a base case raises RecursionError.

5

Topic 5

Scope and lifetime of variables

ComparisonScope of variables
Defined
Lifetime

Local

Inside a function

While the function runs

Enclosing

In an outer function, used by a nested function (nonlocal to modify)

While the outer function's frame exists

Global

At module level (global to modify inside a function)

Until the program ends

Built-in

Names provided by Python (len, print)

Always

  • Python resolves names by the LEGB rule: Local, Enclosing, Global, Built-in.

Example

The global keyword: count = 0; def inc(): global count; count += 1 — calling inc() twice makes count 2. Without global, Python raises UnboundLocalError because count would be treated as local.

Exam tip

LEGB rule: Python looks for names in Local, Enclosing, Global, then Built-in scope.

6

Topic 6

Creating and importing modules

python# mymath.py — a module is any .py file
PI = 3.14159
def circle_area(r):
    return PI * r * r

# main.py
import mymath
print(mymath.circle_area(2))
from mymath import circle_area as ca
print(ca(3))
  • if __name__ == "__main__": runs code only when the file is executed directly, not when imported.

Example

Using your own module: after saving mymath.py, another file in the same folder writes from mymath import circle_area and calls circle_area(2) to get about 12.57. import mymath as mm lets you write mm.PI.

Exam tip

A module is just a .py file; if __name__ == "__main__": runs code only when the file is run directly.

7

Topic 7

Standard modules and packages

Key termsStandard library modules
math
sqrt, factorial, pi, ceil, floor
random
random, randint, choice, shuffle
datetime
date, time, timedelta
os and sys
Files, directories, environment, command-line arguments
statistics
mean, median, mode, stdev
json and csv
Read and write data formats
re
Regular expressions
  • Package: a folder of modules (with an optional __init__.py) imported with dot notation — from college.exams import results. Third-party packages (NumPy, pandas, requests) are installed with pip.

Example

Using the standard library: import math; math.sqrt(81) gives 9.0; import random; random.randint(1, 6) simulates a dice; from datetime import date; date.today() gives today's date.

Exam tip

A package is a folder of modules (traditionally with an __init__.py file).

8

Topic 8

Built-in exceptions and handling

An exception is a run-time error that stops the program unless handled.

pythontry:
    a = int(input()); b = int(input())
    print(a / b)
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("Enter numbers only")
else:
    print("Division done")               # runs if no exception
finally:
    print("Program finished")            # always runs

raise throws an exception yourself: if age < 0: raise ValueError("Age cannot be negative").

Example

Handling bad input: try: n = int(input()); print(100 / n) except ValueError: print("Enter a number") except ZeroDivisionError: print("Cannot divide by zero") finally: print("Done") — entering 0 prints the second message and then Done.

Exam tip

Order: try → except (one or more) → else (runs if no exception) → finally (always runs).

9

Topic 9

User-defined exceptions

pythonclass InvalidMarksError(Exception):
    """Raised when marks are outside 0–100."""
    pass

def set_marks(m):
    if not 0 <= m <= 100:
        raise InvalidMarksError(f"Marks {m} out of range")
    return m

try:
    set_marks(120)
except InvalidMarksError as e:
    print("Error:", e)
else:
    print("Saved")
finally:
    print("Done")

Example

Raising your own exception: if not 0 <= marks <= 100: raise InvalidMarksError("Marks must be 0–100"). Calling code catches it with except InvalidMarksError as e: print(e).

Exam tip

Custom exceptions should inherit from Exception.

Key terms

Function
Named block of reusable code
Lambda
Anonymous single-expression function
Recursion
Function calling itself
Module
Python file containing reusable definitions
Exception
Error event raised during execution

Quick revision

  • Built-in functions; def, return, docstrings.
  • Positional, keyword, default, variable-length arguments.
  • Lambda with map, filter, sorted; pass by object reference.
  • Recursion and base case; LEGB scope; global and nonlocal.
  • Modules, import forms, __name__; standard modules; packages; try, except, else, finally, raise; custom exceptions.

Important exam questions

Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).

Short-answer questions

  1. Q1.Distinguish arguments and parameters.
  2. Q2.Write a lambda function to square a number.
  3. Q3.What is the LEGB rule?
  4. Q4.What is the purpose of if __name__ == "__main__"?
  5. Q5.Distinguish a module and a package.
  6. Q6.When does the else block of a try statement run?

Long-answer questions

  1. Q1.Explain types of function arguments with examples.
  2. Q2.Explain recursion with factorial and Fibonacci programs.
  3. Q3.Explain modules and packages in Python.
  4. Q4.Explain exception handling, including user-defined exceptions.

Stuck on this unit?

Message SBS on WhatsApp for help with Fundamentals of Computer and Programming in Python, or to ask about studying M.Sc IT at Synetic.

Planning your M.Sc IT in Ludhiana? See the M.Sc IT at SBS →

WhatsApp us