0% found this document useful (0 votes)
11 views14 pages

Python Module Programs for Class XI

The document provides a series of Python module programs aimed at Class XI students, covering various tasks such as calculating square roots, generating random numbers, and performing arithmetic operations. Each program includes a solution, an explanation of the code, and demonstrates the use of different Python modules like math, random, and datetime. The document serves as a practical guide for students to learn Python programming through hands-on examples.

Uploaded by

souviksarkarhere
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views14 pages

Python Module Programs for Class XI

The document provides a series of Python module programs aimed at Class XI students, covering various tasks such as calculating square roots, generating random numbers, and performing arithmetic operations. Each program includes a solution, an explanation of the code, and demonstrates the use of different Python modules like math, random, and datetime. The document serves as a practical guide for students to learn Python programming through hands-on examples.

Uploaded by

souviksarkarhere
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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.

Common questions

Powered by AI

Generating a secure six-digit OTP can be achieved by concatenating six random digits using random.randint(0,9) within a loop. An alternative, ensuring the first digit is not zero, could use random.randrange(100000, 1000000), generating an OTP that avoids leading zeroes, which some systems might mishandle.

Statistical calculations such as mean, median, and mode can be performed using the statistics module. Given a list, use statistics.mean(data) for the mean, statistics.median(data) for the median, and statistics.mode(data) for the mode. These functions ease the process over traditional manual computations.

LCM can be efficiently calculated using GCD with the formula abs(a*b)//math.gcd(a, b). This algorithm leverages gcd's simpler calculations to derive lcm, making it computationally more efficient than directly iterating to find the least common multiple through factors.

Python modules allow for separating functions into different files that can be imported and reused in multiple programs, promoting code modularity and reusability. For example, creating a module with functions like add, sub, mul, and div can eliminate redundant code and make maintenance easier by updating functions in a single module file rather than multiple scripts.

To calculate days until the next birthday, first parse the birth date into day and month. Construct the birthday date object for the current year, and if the date has passed, adjust for the next year. Calculate the difference between the current date and this determined birthday date to yield days remaining.

The current month’s calendar can be displayed using the calendar and datetime modules. First, obtain the current date using date.today() from datetime. Then, use calendar.month(year, month) where year and month are derived from the current date to generate and display a formatted string of the current month.

Python can dynamically select and display a motivational quote by storing quotes in a list and using random.choice to pick one at random each script execution. This method leverages Python's robust random module to introduce variability in content faced by users.

To simulate a dice roll, use random.randint(1, 6). This function returns a random integer between the values 1 and 6, inclusive, representing the faces of a standard die.

Temperature conversion functions, like those for Celsius to Fahrenheit and vice versa, centralize the conversion formulas, facilitating clear, reusable code. They should be structured within a module for easy access and utilization across programs by importing the necessary functions. For example, by placing functions cel_to_fah(c) and fah_to_cel(f) in convert.py, they can be easily imported as needed.

The math module uses math.sqrt(x) to calculate the positive square root of a number x. If the input is negative, math.sqrt will raise a ValueError as it cannot handle negative inputs relative to real number square roots.

You might also like