Python Modules Practice Questions with Solutions

Python modules help you organize code into reusable files. Python also provides many built-in modules, such as math, random, and datetime, that make programming easier. In this practice set, you’ll learn how to import modules, use built-in functions, create your own modules, and solve beginner-friendly Python programs. Python Modules practice questions with solutions help to understand the concepts.


1. Python Program to Import the Math Module

Problem Statement

Write a Python program to import the math module and find the square root of 81.

Python Solution

import math

result = math.sqrt(81)

print(result)

Sample Output

9.0

Explanation

The math module provides mathematical functions like sqrt().

Concepts Covered

  • import
  • math module
  • sqrt()

2. Python Program to Find the Value of Pi

Problem Statement

Write a Python program to print the value of π using the math module.

Python Solution

import math

print(math.pi)

Sample Output

3.141592653589793

Explanation

The math.pi constant returns the value of π.

Concepts Covered

  • math.pi

3. Python Program to Generate a Random Number

Problem Statement

Write a Python program to generate a random number between 1 and 100.

Python Solution

import random

print(random.randint(1, 100))

Sample Output

57

Note: Your output may be different because the number is generated randomly.

Explanation

The randint() function returns a random integer within the specified range.

Concepts Covered

  • random module
  • randint()

4. Python Program to Choose a Random Item from a List

Problem Statement

Write a Python program to randomly select a fruit from a list.

Python Solution

import random

fruits = ["Apple", "Banana", "Mango", "Orange"]

print(random.choice(fruits))

Sample Output

Mango

Note: The output may vary each time you run the program.

Explanation

The choice() function returns a random element from a sequence.

Concepts Covered

  • random.choice()

5. Python Program to Display the Current Date

Problem Statement

Write a Python program to print the current date using the datetime module.

Python Solution

from datetime import date

today = date.today()

print(today)

Sample Output

2026-07-31

Explanation

The today() method returns the current system date.

Concepts Covered

  • datetime module
  • date.today()

6. Python Program to Import a Specific Function

Problem Statement

Write a Python program to import only the sqrt() function from the math module.

Python Solution

from math import sqrt

print(sqrt(144))

Sample Output

12.0

Explanation

You can import only the required function instead of the entire module.

Concepts Covered

  • from…import

7. Python Program to Import a Module with an Alias

Problem Statement

Write a Python program to import the math module using the alias m.

Python Solution

import math as m

print(m.factorial(5))

Sample Output

120

Explanation

The as keyword creates a shorter alias for a module.

Concepts Covered

  • import as
  • Module Alias

8. Python Program to Create a Custom Module

Problem Statement

Create a custom module named calculator.py with an add() function and use it in another Python file.

calculator.py

def add(a, b):
    return a + b

main.py

import calculator

print(calculator.add(15, 10))

Sample Output

25

Explanation

Custom modules help organize reusable code into separate files.

Concepts Covered

  • Custom Module
  • import

9. Python Program to Generate a Random Floating-Point Number

Problem Statement

Write a Python program to generate a random floating-point number between 0 and 1.

Python Solution

import random

print(random.random())

Sample Output

0.684527913

Note: The output will be different every time you run the program.

Explanation

The random() function returns a random float between 0.0 and 1.0.

Concepts Covered

  • random.random()

10. Python Program to Calculate the Factorial of a Number Using the Math Module

Problem Statement

Write a Python program to calculate the factorial of 6 using the math module.

Python Solution

import math

print(math.factorial(6))

Sample Output

720

Explanation

The factorial() function returns the factorial of a non-negative integer.

Concepts Covered

  • math.factorial()

11. Python Program to Calculate Factorial Using the math Module

Problem Statement

Write a Python program that accepts a number from the user and calculates its factorial using the built-in math module.

Python Solution

import math

number = int(input("Enter a Number: "))

factorial = math.factorial(number)

print("Factorial =", factorial)

Sample Output

Enter a Number: 6

Factorial = 720

Explanation

The math module provides the factorial() function, which calculates the factorial of a non-negative integer without manually writing loops or recursion.

Concepts Covered

  • math Module
  • import Statement
  • factorial()
  • User Input

12. Python Program to Generate Random OTP Using the random Module

Problem Statement

Write a Python program to generate a random 6-digit OTP using the random module.

Python Solution

import random

otp = random.randint(100000, 999999)

print("Generated OTP:", otp)

Sample Output

Generated OTP: 648293

Note: Your output will be different every time because the OTP is generated randomly.

Explanation

The random.randint() function generates a random integer between the specified range. This technique is commonly used for OTP generation and verification systems.

Concepts Covered

  • random Module
  • randint()
  • Random Number Generation
  • Security Basics

13. Python Program to Display Today’s Date and Current Time Using datetime Module

Problem Statement

Write a Python program to display the current date and time using the built-in datetime module.

Python Solution

from datetime import datetime

current = datetime.now()

print("Current Date and Time:")
print(current)

Sample Output

Current Date and Time:
2026-08-03 11:45:28.917654

Explanation

The datetime.now() method returns the current system date and time. It is widely used in logging systems, attendance software, and scheduling applications.

Concepts Covered

  • datetime Module
  • datetime.now()
  • Date and Time
  • from…import Statement

14. Python Program to Calculate the Average Using the statistics Module

Problem Statement

Write a Python program to calculate the average (mean) of a list of numbers using the statistics module.

Python Solution

import statistics

numbers = [25, 35, 40, 55, 65, 80]

average = statistics.mean(numbers)

print("Average =", average)

Sample Output

Average = 50

Explanation

The statistics.mean() function calculates the arithmetic mean of all values in the list. This module is commonly used in data analysis and reporting.

Concepts Covered

  • statistics Module
  • mean()
  • Lists
  • Data Analysis

15. Python Program to Find the Square Root of Multiple Numbers Using the math Module

Problem Statement

Write a Python program to calculate the square root of multiple numbers stored in a list using the math module.

Python Solution

import math

numbers = [16, 25, 36, 49, 64]

print("Square Roots:\n")

for number in numbers:

    print(f"{number} → {math.sqrt(number)}")

Sample Output

Square Roots:

16 → 4.0
25 → 5.0
36 → 6.0
49 → 7.0
64 → 8.0

Explanation

The math.sqrt() function calculates the square root of each number in the list. A loop is used to process multiple values efficiently.

Concepts Covered

  • math Module
  • sqrt()
  • for Loop
  • List Processing

16. Python Program to Display the Calendar of a Given Month Using the calendar Module

Problem Statement

Write a Python program that accepts a year and month from the user and displays the corresponding calendar using the built-in calendar module.

Python Solution

import calendar

year = int(input("Enter Year: "))
month = int(input("Enter Month (1-12): "))

print("\nCalendar:\n")

print(calendar.month(year, month))

Sample Output

Enter Year: 2026
Enter Month (1-12): 8

Calendar:

    August 2026
Mo Tu We Th Fr Sa Su
               1  2
3  4  5  6  7  8  9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31

Explanation

The calendar.month() function generates a formatted calendar for the specified month and year.

Concepts Covered

  • calendar Module
  • month()
  • User Input
  • Calendar Generation

17. Python Program to Check Whether a File Exists Using the os Module

Problem Statement

Write a Python program to check whether a file exists using the built-in os module.

Python Solution

import os

filename = input("Enter File Name: ")

if os.path.exists(filename):

    print("File Exists.")

else:

    print("File Not Found.")

Sample Output

Enter File Name: report.txt

File Exists.

Explanation

The os.path.exists() function returns True if the specified file or folder exists; otherwise, it returns False.

Concepts Covered

  • os Module
  • path.exists()
  • File Validation
  • Conditional Statements

18. Python Program to Shuffle a List Using the random Module

Problem Statement

Write a Python program to randomly shuffle the elements of a list using the random module.

Python Solution

import random

numbers = [10, 20, 30, 40, 50, 60]

random.shuffle(numbers)

print("Shuffled List:")

print(numbers)

Sample Output

Shuffled List:

[40, 20, 60, 10, 50, 30]

Note: The output will be different each time because the list is shuffled randomly.

Explanation

The random.shuffle() function rearranges the elements of a list in random order.

Concepts Covered

  • random Module
  • shuffle()
  • Lists
  • Randomization

19. Python Program to Measure Program Execution Time Using the time Module

Problem Statement

Write a Python program to measure how long a task takes to execute using the time module.

Python Solution

import time

start = time.time()

for number in range(1, 1000001):

    square = number ** 2

end = time.time()

print("Execution Time:")

print(round(end - start, 4), "seconds")

Sample Output

Execution Time:

0.1428 seconds

Note: The execution time depends on your computer’s hardware and may vary.

Explanation

The time.time() function records the current timestamp. By subtracting the start time from the end time, you can measure the total execution time of the program.

Concepts Covered

  • time Module
  • Performance Measurement
  • Loops
  • Benchmarking

20. Python Program to Generate All Possible Pair Combinations Using itertools Module

Problem Statement

Write a Python program to generate all possible two-element combinations from a list using the itertools module.

Python Solution

from itertools import combinations

numbers = [1, 2, 3, 4]

result = combinations(numbers, 2)

print("Possible Combinations:\n")

for item in result:

    print(item)

Sample Output

Possible Combinations:

(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)

Explanation

The itertools.combinations() function generates all unique combinations of a specified length without repeating elements.

Concepts Covered

  • itertools Module
  • combinations()
  • Iterators
  • Combinatorial Programming

21. Python Program to Create and Import a Custom Module

Problem Statement

Write a Python program to create a custom module named calculator.py that performs addition, subtraction, multiplication, and division. Import the module into another Python file and use its functions.

Step 1: Create calculator.py

def add(a, b):
    return a + b


def subtract(a, b):
    return a - b


def multiply(a, b):
    return a * b


def divide(a, b):
    return a / b

Step 2: Create main.py

import calculator

print("Addition =", calculator.add(20, 10))

print("Subtraction =", calculator.subtract(20, 10))

print("Multiplication =", calculator.multiply(20, 10))

print("Division =", calculator.divide(20, 10))

Sample Output

Addition = 30
Subtraction = 10
Multiplication = 200
Division = 2.0

Explanation

A custom module is created using reusable functions. The import statement allows these functions to be used in another Python file without rewriting the code.

Concepts Covered

  • Custom Module
  • import Statement
  • User-defined Functions
  • Code Reusability

22. Python Program to Display System Information Using the sys Module

Problem Statement

Write a Python program to display the current Python version and command-line arguments using the sys module.

Python Solution

import sys

print("Python Version:\n")

print(sys.version)

print("\nCommand Line Arguments:")

print(sys.argv)

Sample Output

Python Version:

3.13.2 (main, Jan 15 2026, ...)

Command Line Arguments:

['main.py']

Explanation

The sys module provides access to system-specific information such as the Python version and command-line arguments.

Concepts Covered

  • sys Module
  • version
  • argv
  • System Information

23. Python Program to Count Word Frequency Using the collections Module

Problem Statement

Write a Python program to count the frequency of words in a sentence using the collections.Counter class.

Python Solution

from collections import Counter

sentence = "python is easy python is powerful python is popular"

words = sentence.split()

frequency = Counter(words)

print("Word Frequency:\n")

for word, count in frequency.items():

    print(word, ":", count)

Sample Output

Word Frequency:

python : 3
is : 3
easy : 1
powerful : 1
popular : 1

Explanation

The Counter class automatically counts how many times each element appears in a collection, making frequency analysis much easier.

Concepts Covered

  • collections Module
  • Counter
  • Word Frequency
  • Dictionaries

24. Python Program to Generate an Infinite Counter Using itertools Module

Problem Statement

Write a Python program to generate an infinite sequence of numbers starting from 100 using the itertools.count() function.

Python Solution

from itertools import count

counter = count(start=100)

for number in counter:

    print(number)

    if number == 110:

        break

Sample Output

100
101
102
103
104
105
106
107
108
109
110

Explanation

The count() function creates an infinite iterator. The loop is manually stopped using the break statement after reaching 110.

Concepts Covered

  • itertools Module
  • count()
  • Infinite Iterator
  • break Statement

25. Python Program to Build a Student Performance Analyzer Using Modules

Problem Statement

Write a Python program that uses the statistics module to calculate the average, highest, lowest, and median marks of students.

Python Solution

import statistics

marks = [85, 72, 96, 88, 91, 75, 83]

print("Average Marks:", statistics.mean(marks))

print("Highest Marks:", max(marks))

print("Lowest Marks:", min(marks))

print("Median Marks:", statistics.median(marks))

Sample Output

Average Marks: 84.29

Highest Marks: 96

Lowest Marks: 72

Median Marks: 85

Explanation

The program combines Python’s built-in functions with the statistics module to perform a complete analysis of student marks. This type of analysis is commonly used in educational software and reporting systems.

Concepts Covered

  • statistics Module
  • mean()
  • median()
  • max()
  • min()
  • Data Analysis

Frequently Asked Questions (FAQs)


1. What is a module in Python?

A module is a Python file (.py) that contains functions, classes, variables, and executable code. Modules help organize code into reusable components, making programs easier to maintain and manage.

Example:

import math

print(math.sqrt(64))

Output

8.0

Concepts Covered

  • Python Modules
  • import Statement
  • Code Reusability

2. What is the difference between a module and a package in Python?

A module is a single Python file, whereas a package is a collection of related modules organized inside a directory.

ModulePackage
Single .py fileFolder containing multiple modules
Contains Python codeContains related modules
Imported directlyCan contain sub-packages
Example: math.pyExample: numpy, pandas

Packages are useful for organizing large Python projects.


3. How do you import a module in Python?

Python provides multiple ways to import modules.

Import Entire Module

import math

print(math.factorial(5))

Import Specific Function

from math import sqrt

print(sqrt(81))

Import Using Alias

import math as m

print(m.pi)

Each method has different use cases depending on your project.


4. What are built-in modules in Python?

Built-in modules are modules that come pre-installed with Python. They provide ready-to-use functions for common programming tasks.

Some popular built-in modules include:

  • math
  • random
  • datetime
  • os
  • sys
  • statistics
  • calendar
  • itertools
  • collections
  • time

These modules eliminate the need to write common functionality from scratch.


5. What is the difference between import and from ... import?

importfrom ... import
Imports the entire moduleImports only selected functions or objects
Requires the module name before function callsFunction can be called directly
Better for avoiding name conflictsMore concise for specific functions

Example

import math

print(math.sqrt(25))
from math import sqrt

print(sqrt(25))

6. What is module aliasing in Python?

Module aliasing means assigning a shorter name to a module using the as keyword. It makes code easier to read and write.

Example

import statistics as stats

numbers = [10, 20, 30, 40]

print(stats.mean(numbers))

Alias names are widely used in libraries such as:

  • numpy as np
  • pandas as pd
  • matplotlib.pyplot as plt

7. How do you create a custom module in Python?

A custom module is simply a Python file containing reusable code.

calculator.py

def add(a, b):
    return a + b

main.py

import calculator

print(calculator.add(15, 25))

This approach improves code organization and promotes reusability across multiple Python programs.


8. Why are modules important in Python?

Modules provide several benefits:

  • Reduce code duplication
  • Improve code organization
  • Increase code reusability
  • Simplify debugging
  • Improve maintainability
  • Encourage modular programming
  • Make teamwork easier on large projects

Most professional Python applications are built using multiple modules.


9. Which Python modules are most commonly used in real-world projects?

Some of the most widely used modules are:

  • math
  • random
  • datetime
  • os
  • sys
  • statistics
  • collections
  • itertools
  • csv
  • json
  • pathlib
  • logging

For data science and machine learning, popular third-party modules include:

  • NumPy
  • Pandas
  • Matplotlib
  • Scikit-learn
  • TensorFlow

Learning these modules significantly increases your Python development skills.


10. Why are Python modules important for interviews and real-world projects?

Python modules are a fundamental concept because they enable developers to build organized, scalable, and reusable applications.

Common interview questions focus on:

  • Built-in modules
  • Custom modules
  • Packages
  • import statement
  • from ... import
  • Module aliasing
  • Standard library modules
  • Creating reusable code
  • Package structure
  • Best practices for module organization

Python modules are extensively used in Web Development, Data Science, Machine Learning, Artificial Intelligence, Automation, DevOps, Cloud Computing, API Development, Desktop Applications, and Enterprise Software. Mastering modules helps you write clean, maintainable, and professional-quality Python code, making it an essential skill for coding interviews and real-world software development.

Chapter Summary

After completing this chapter, you have learned:

  • Importing modules
  • Using the math module
  • Using the random module
  • Using the datetime module
  • Importing specific functions
  • Using module aliases
  • Creating custom modules
  • Generating random numbers
  • Working with mathematical functions

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top