? Class 12 Python Notes
? Class 12 Python Notes
✅ What is a Module?
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
import math as m
print(m.factorial(5)) # Output: 120
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
Syntax of try-except
try:
# Code that might cause error
except ExceptionType:
# Code to handle the error
✅ 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
✅ 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.
File: calculator.py
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
greet.py
def hello():
print("Welcome to Class 12 Computer Science!")
main.py
import greet
greet.hello()
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!")
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.")
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)