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)

3 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
ProcessException handling in Python
  1. 1try

    Code that might fail

  2. 2except

    Handle a specific error

  3. 3else

    Runs if no error occurred

  4. 4finally

    Always runs: clean up

  5. 5raise

    Throw your own exception

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")
2

Topic 2

Anonymous functions and scope

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.
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]
4

Topic 4

Recursion

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

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

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.

WhatsApp us