Unit 3: Functions, modules and exception handling
Fundamentals of Computer and Programming in Python notes · PTU syllabus (PGCA1902)
On this page
- Unit summary
- Built-in and user-defined functions
- Anonymous functions and scope
- Pass by value vs pass by reference
- Recursion
- Scope and lifetime of variables
- Creating and importing modules
- Standard modules and packages
- Built-in exceptions and handling
- User-defined exceptions
- Key terms
- Quick revision
- 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
- 1try
Code that might fail
- 2except
Handle a specific error
- 3else
Runs if no error occurred
- 4finally
Always runs: clean up
- 5raise
Throw your own exception
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")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
.pyfile of functions; useimport mymoduleorfrom mymodule import area.
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]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()).
Topic 5
Scope and lifetime of variables
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.
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.
Topic 7
Standard modules and packages
- 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.
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 runsraise throws an exception yourself: if age < 0: raise ValueError("Age cannot be negative").
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
- Q1.Distinguish arguments and parameters.
- Q2.Write a lambda function to square a number.
- Q3.What is the LEGB rule?
- Q4.What is the purpose of if __name__ == "__main__"?
- Q5.Distinguish a module and a package.
- Q6.When does the else block of a try statement run?
Long-answer questions
- Q1.Explain types of function arguments with examples.
- Q2.Explain recursion with factorial and Fibonacci programs.
- Q3.Explain modules and packages in Python.
- 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.
