Class 12 Python Notes
Topic 1: Modules in Python
Topic 2: Exception Handling (try-except block)
Topic 1: Modules in Python
✅ What is a Module?
A module is a file containing Python definitions and statements (functions, variables, or
classes) which can be reused in other programs.
It helps in code reusability, maintainability, and organization.
Types of Modules:
Type Example
Built-in Modules math, random, datetime, os, etc.
User-defined Modules Created by the programmer
Importing Modules
1. import module_name
import math
print(math.sqrt(25)) # Output: 5.0
2. import module_name as alias
import math as m
print(m.factorial(5)) # Output: 120
3. from module_name import function_name
from math import pow
print(pow(2, 3)) # Output: 8.0
4. from module_name import *
from math import *
print(sin(90)) # Uses math.sin
Creating a User-defined Module
File: greet.py
def welcome(name):
print("Welcome", name)
File: main.py
import greet
greet.welcome("Farhat")
✅ Advantages of Using Modules
• Code reuse
• Better code organization
• Easy to maintain and debug
• Collaboration in large projects
Topic 2: Exception Handling using try-except
✅ What is an Exception?
An exception is an error that occurs during the execution of a program.
Examples: divide by zero, invalid input, file not found, etc.
Common Python Exceptions
Exception Type Cause
ZeroDivisionError Division by zero
ValueError Invalid value (e.g., converting "abc" to int)
TypeError Invalid operation on data types
FileNotFoundError File not found
IndexError Index out of range in a list
KeyError Invalid key access in a dictionary
Syntax of try-except
try:
# Code that might cause error
except ExceptionType:
# Code to handle the error
✅ Example 1: Divide by Zero
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
print("Result:", a / b)
except ZeroDivisionError:
print("Cannot divide by zero!")
✅ Example 2: Handling Multiple Exceptions
try:
num = int(input("Enter a number: "))
print("Reciprocal:", 1/num)
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
Using else and finally
try:
num = int(input("Enter a number: "))
print("Square:", num * num)
except ValueError:
print("Invalid number!")
else:
print("Operation successful.")
finally:
print("This block is always executed.")
✅ Summary of Keywords:
Keyword Purpose
try Block of code to monitor for errors
except Block that handles the error
else Executes if no exception occurred
finally Always executes, whether exception occurred or not
Real-life Example: File Handling with Exception
try:
f = open("data.txt", "r")
content = f.read()
print(content)
f.close()
except FileNotFoundError:
print("File not found!")
✅ Practice Questions:
1. Write a module that contains a function to find the factorial of a number. Import and
use it in another file.
2. Write a program that handles ValueError if the user enters a non-numeric input.
3. Create a program that opens a file and handles the FileNotFoundError if it doesn't
exist.
Part A: Modules – Questions with Answers
✅ Q1. Create a user-defined module calculator.py with functions for
addition and subtraction. Import and use them in another file.
File: calculator.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
File: main.py
import calculator
x = 10
y = 5
print("Addition:", calculator.add(x, y))
print("Subtraction:", calculator.subtract(x, y))
✅ Q2. Write a Python program to import the math module and calculate the
area of a circle.
import math
radius = float(input("Enter the radius of the circle: "))
area = math.pi * radius ** 2
print("Area of circle =", area)
✅ Q3. Create a module greet.py with a function hello() that prints a
welcome message. Import and call it in another file.
greet.py
def hello():
print("Welcome to Class 12 Computer Science!")
main.py
import greet
greet.hello()
Part B: Exception Handling – Questions with Answers
✅ Q4. Write a program that takes two numbers and divides them. Handle
ZeroDivisionError.
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a / b
print("Result =", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
✅ Q5. Write a program that takes input and converts it to an integer.
Handle ValueError if the input is not a number.
try:
num = int(input("Enter a number: "))
print("Square:", num ** 2)
except ValueError:
print("Invalid input! Please enter a valid number.")
✅ Q6. Write a program to open and read a file. Handle FileNotFoundError.
try:
f = open("notes.txt", "r")
content = f.read()
print(content)
f.close()
except FileNotFoundError:
print("File not found. Please check the filename.")
✅ Q7. Write a program to perform division and handle both ValueError and
ZeroDivisionError.
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Result:", a / b)
except ValueError:
print("Please enter numbers only.")
except ZeroDivisionError:
print("Denominator cannot be zero.")
✅ Q8. Demonstrate the use of finally block in exception handling.
try:
f = open("data.txt", "r")
print(f.read())
except FileNotFoundError:
print("File not found.")
finally:
print("This block is always executed.")
✅ Q9. Write a function to calculate square root of a number using math
module and handle error if a negative number is passed.
import math
try:
num = float(input("Enter a number: "))
if num < 0:
raise ValueError("Negative number not allowed for square root.")
print("Square root:", math.sqrt(num))
except ValueError as e:
print("Error:", e)
✅ Q10. Write a program to add two numbers. Handle any unexpected
exception using a generic except block.
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Sum =", a + b)
except Exception as e:
print("Something went wrong:", e)