Python Module Programs with Detailed
Solutions (Class XI)
1. Find the square root of a number using the math module.
Solution:
import math
num = float(input('Enter a number: '))
result = [Link](num)
print('Square root of', num, 'is', result)
Explanation:
[Link](x) returns the positive square root of x. We convert input to float to handle
decimals. If a negative number is given, [Link] will raise a ValueError.
2. Generate 5 random integers between 10 and 50 using the random module.
Solution:
import random
for i in range(5):
print([Link](10, 50))
Explanation:
[Link](a, b) returns a random integer N such that a <= N <= b. We run it 5 times in
a loop.
3. Calculate the area of a circle using [Link].
Solution:
import math
r = float(input('Enter radius: '))
area = [Link] * r * r
print('Area of circle:', area)
Explanation:
[Link] provides an accurate value of π. Formula for area is πr². Use float to accept non-
integer radii.
4. Import only sqrt and pow from math and use them.
Solution:
from math import sqrt, pow
n = float(input('Enter a number: '))
print('Square root:', sqrt(n))
print('n squared:', pow(n, 2))
Explanation:
from module import name allows using functions without the module prefix. pow(x, y)
returns x**y (as float).
5. Print today's date and current time using datetime module.
Solution:
from datetime import datetime
now = [Link]()
print('Current date and time:', [Link]('%d-%m-%Y %H:%M:%S'))
Explanation:
[Link]() returns current local date and time. strftime formats the output (day-
month-year hours:minutes:seconds).
6. Find mean, median and mode of a list using statistics module.
Solution:
import statistics
data = [10, 20, 20, 30, 40]
print('Mean:', [Link](data))
print('Median:', [Link](data))
print('Mode:', [Link](data))
Explanation:
[Link] computes average. median returns middle value (or average of two middle
values). mode returns the most common value; will raise StatisticsError if no unique mode.
7. Display calendar for the current month.
Solution:
import calendar
from datetime import date
today = [Link]()
print([Link]([Link], [Link]))
Explanation:
[Link](year, month) returns a formatted string for that month's calendar. Use
[Link]() to get current year and month.
8. Simulate rolling a dice using [Link]().
Solution:
import random
roll = [Link](1, 6)
print('Dice shows:', roll)
Explanation:
A standard die has faces 1–6; randint(1, 6) simulates one roll.
9. Generate 10 random floats between 0 and 1 using [Link]().
Solution:
import random
for _ in range(10):
print([Link]())
Explanation:
[Link]() returns a float in the half-open interval [0.0, 1.0). Useful for probabilistic
experiments.
10. Find factorial using [Link]().
Solution:
import math
n = int(input('Enter a non-negative integer: '))
print('Factorial:', [Link](n))
Explanation:
[Link](n) computes n! for non-negative integers. It raises ValueError for negative
inputs.
11. Create a module [Link] with add, sub, mul, div functions and use it.
Solution ([Link]):
# [Link]
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, b):
if b == 0:
raise ValueError('Division by zero')
return a / b
Usage ([Link]):
import mymath
x = float(input('x: '))
y = float(input('y: '))
print('Add:', [Link](x, y))
print('Sub:', [Link](x, y))
print('Mul:', [Link](x, y))
print('Div:', [Link](x, y))
Explanation:
We place functions in a separate .py file and import it. This demonstrates modular code and
reuse.
12. Create [Link] for Celsius↔Fahrenheit conversions.
Solution ([Link]):
# [Link]
def cel_to_fah(c):
return (c * 9/5) + 32
def fah_to_cel(f):
return (f - 32) * 5/9
Usage:
from convert import cel_to_fah, fah_to_cel
c = float(input('Celsius: '))
print('Fahrenheit:', cel_to_fah(c))
Explanation:
Temperature conversion formulas used inside a module and imported where needed.
13. Create [Link] with area functions for circle, rectangle, triangle.
Solution ([Link]):
# [Link]
def area_circle(r):
import math
return [Link] * r * r
def area_rectangle(l, b):
return l * b
def area_triangle(b, h):
return 0.5 * b * h
Usage:
from geometry import area_circle, area_rectangle, area_triangle
print(area_circle(3))
Explanation:
Each function computes area using standard formulas and can be imported separately.
14. Create a module [Link] with isPrime(n) function and test it.
Solution ([Link]):
# [Link]
def isPrime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0:
return False
i=3
while i * i <= n:
if n % i == 0:
return False
i += 2
return True
Usage:
from isprime import isPrime
n = int(input('Enter n: '))
print(isPrime(n))
Explanation:
Simple efficient primality test for moderate n using trial division by odd numbers up to
sqrt(n).
15. Create a package with [Link] and [Link] and import both.
Solution (package structure):
mypkg/
__init__.py
[Link]
[Link]
# [Link]
def add(a,b): return a+b
# [Link]
import math
def sin_deg(x): return [Link]([Link](x))
Usage:
from mypkg import arithmetic, trigonometry
print([Link](2,3))
print(trigonometry.sin_deg(30))
Explanation:
A package is a folder with __init__.py; it groups related modules for organized code.
16. Find sine, cosine, and tangent of an angle in degrees.
Solution:
import math
angle = float(input('Angle in degrees: '))
rad = [Link](angle)
print('sin:', [Link](rad))
print('cos:', [Link](rad))
print('tan:', [Link](rad))
Explanation:
math functions accept radians, so convert degrees to radians using [Link]().
17. Generate a random number divisible by 5 between 100 and 200.
Solution:
import random
while True:
n = [Link](100, 200)
if n % 5 == 0:
print(n)
break
Explanation:
Keep generating until a number divisible by 5 is found. Alternatively, pick from a sequence:
[Link](range(100, 201, 5)).
18. Pick a random element from a list of fruits.
Solution:
import random
fruits = ['apple','banana','mango','orange']
print([Link](fruits))
Explanation:
[Link](list) returns a random element from a non-empty sequence.
19. Find LCM and GCD of two numbers using [Link]().
Solution:
import math
def lcm(a, b):
return abs(a*b)//[Link](a,b)
x = int(input('x: '))
y = int(input('y: '))
print('GCD:', [Link](x, y))
print('LCM:', lcm(x, y))
Explanation:
GCD from [Link]; LCM computed using abs(a*b)/gcd. Works for integers including
negatives.
20. Generate a random 6-digit OTP.
Solution:
import random
otp = ''.join(str([Link](0,9)) for _ in range(6))
print('OTP:', otp)
Explanation:
Concatenate six random digits. Alternatively use [Link](100000, 1000000) to
ensure leading digit non-zero.
21. Print current date in DD-MM-YYYY format.
Solution:
from datetime import date
print([Link]().strftime('%d-%m-%Y'))
Explanation:
[Link]() returns current date; strftime formats it.
22. Display the current day of the week.
Solution:
from datetime import date
print([Link]().strftime('%A'))
Explanation:
%A gives the full weekday name like 'Thursday'.
23. Calculate number of days between two dates.
Solution:
from datetime import datetime
fmt = '%d-%m-%Y'
d1 = [Link](input('Date1 (DD-MM-YYYY): '), fmt)
d2 = [Link](input('Date2 (DD-MM-YYYY): '), fmt)
print('Days difference:', abs((d2 - d1).days))
Explanation:
[Link] parses strings to datetime objects. Subtraction gives timedelta; .days
yields integer days.
24. Print the date 100 days before today.
Solution:
from datetime import date, timedelta
print(([Link]() - timedelta(days=100)).strftime('%d-%m-%Y'))
Explanation:
timedelta represents duration; subtracting finds past date.
25. Display current time in HH:MM:SS format.
Solution:
from datetime import datetime
print([Link]().strftime('%H:%M:%S'))
Explanation:
strftime '%H:%M:%S' gives 24-hour time.
26. Generate 5 random even numbers between 1 and 100.
Solution:
import random
count = 0
while count < 5:
num = [Link](1, 100)
if num % 2 == 0:
print(num)
count += 1
Explanation:
Loop until five even numbers are printed. Alternatively, sample from range(2,101,2) with
[Link].
27. Print square, cube and square root of an entered number.
Solution:
import math
n = float(input('Enter number: '))
print('Square:', n**2)
print('Cube:', n**3)
print('Square root:', [Link](abs(n)))
Explanation:
Use power operators for square and cube. [Link] requires non-negative, so abs used if
desired; but typically restrict input to non-negative for real sqrt.
28. Print a random motivational quote each run.
Solution:
import random
quotes = [
'Believe you can and you're halfway there.',
'Don’t watch the clock; do what it does. Keep going.',
'The only way to do great work is to love what you do.'
print([Link](quotes))
Explanation:
Store quotes in a list and use [Link] to pick one at random.
29. Find number of days left until next birthday.
Solution:
from datetime import date
bday_str = input('Enter your birthday (DD-MM): ')
day, month = map(int, bday_str.split('-'))
now = [Link]()
bday_this_year = date([Link], month, day)
if bday_this_year < now:
bday_next = date([Link] + 1, month, day)
else:
bday_next = bday_this_year
print('Days until birthday:', (bday_next - now).days)
Explanation:
Construct birthday for this year; if already passed, use next year. Subtracting dates gives
days remaining.
30. Generate and show a simple arithmetic question and its answer.
Solution:
import random
ops = ['+', '-', '*']
a = [Link](1, 20)
b = [Link](1, 20)
op = [Link](ops)
question = f'{a} {op} {b} = ?'
answer = eval(f'{a}{op}{b}')
print('Question:', question)
print('Answer:', answer)
Explanation:
Randomly create operands and an operator. eval computes the numeric result. Use caution
with eval in untrusted input—here it's safe because operands and ops are controlled.