Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 10: Python Modules

As programs grow larger, it becomes inefficient to write all the code in a single file. A module is a file containing Python definitions (functions, classes) and statements. Modules allow us to organize code logically and reuse it across multiple projects.

10.1 Importing Modules

There are two primary ways to import modules in Python.

1. Using import <module>

This imports the entire module. To access a function inside the module, you must use the dot notation module_name.function_name().

import math
print(math.sqrt(16))  # Output: 4.0

2. Using from <module> import <function>

This imports specific functions directly into your program’s namespace, meaning you don’t need to use the dot notation.

from math import pi, pow
print(pow(2, 3))      # Output: 8.0
print(pi)             # Output: 3.14159...

(Note: You can use from module import * to import everything without dot notation, but this is generally discouraged as it can clutter your namespace).

10.2 The math Module

The math module provides mathematical functions for floating-point arithmetic.

  • pi: Mathematical constant \(\pi\) (3.141592…).
  • e: Mathematical constant \(e\) (2.718281…).
  • sqrt(x): Returns the square root of x.
  • ceil(x): Returns the smallest integer greater than or equal to x (rounds up).
  • floor(x): Returns the largest integer less than or equal to x (rounds down).
  • pow(x, y): Returns x raised to the power of y.
  • fabs(x): Returns the absolute (positive) floating-point value of x.
  • sin(x), cos(x), tan(x): Returns trigonometric sine, cosine, and tangent of x (x must be in radians).

10.3 The random Module

The random module is used to generate pseudo-random numbers.

  • random(): Returns a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive).
  • randint(a, b): Returns a random integer N such that \(a \le N \le b\) (both inclusive).
  • randrange(start, stop, [step]): Returns a randomly selected element from range(start, stop, step). The stop value is exclusive.

10.4 The statistics Module

The statistics module provides functions to calculate mathematical statistics of numeric data.

  • mean(data): Calculates the arithmetic mean (average) of the data sequence.
  • median(data): Calculates the median (middle value) of the data sequence.
  • mode(data): Calculates the mode (most common value) of the data sequence.

Competency Based Questions

Q1. Predict the Output Assuming the random module has been imported, what are the minimum and maximum possible values that can be generated by the following statement?

x = random.randint(3, 8) - random.randrange(1, 4)

Q2. Find the Error Sonia wrote the following program to find the square root of 25:

import math
ans = sqrt(25)
print(ans)

The code produces a NameError. Why? How can she fix it (provide two different ways)?

Q3. Case-Based Scenario A teacher conducts a quiz for 5 students and records their marks out of 10 in a list: marks = [7, 8, 7, 9, 7]. She wants to find:

  1. The average score of the class.
  2. The score that was achieved by the maximum number of students. Write the Python code using the appropriate module to find these two metrics.

Q4. Assertion-Reasoning

  • Assertion (A): math.ceil(4.2) evaluates to 5, and math.floor(4.8) evaluates to 4.
  • Reason (R): ceil() rounds a number down to the nearest integer, while floor() rounds it up. Choose the correct option: a) Both A and R are true and R is the correct explanation of A. b) Both A and R are true but R is NOT the correct explanation of A. c) A is true but R is false. d) A is false but R is true.

Answers to Competency Based Questions

A1. random.randint(3, 8) can generate values: 3, 4, 5, 6, 7, 8. random.randrange(1, 4) can generate values: 1, 2, 3.

  • Maximum possible value: Max of randint (8) - Min of randrange (1) = 7.
  • Minimum possible value: Min of randint (3) - Max of randrange (3) = 0.

A2. Error: Sonia used import math, which means she must access the function using the dot notation (math.sqrt). She used sqrt directly without importing it specifically into the namespace. Fix 1: Use dot notation.

import math
ans = math.sqrt(25)

Fix 2: Import the function directly.

from math import sqrt
ans = sqrt(25)

A3. The teacher should use the statistics module. The average is the mean, and the most frequent score is the mode.

import statistics

marks = [7, 8, 7, 9, 7]
average_score = statistics.mean(marks)
most_frequent = statistics.mode(marks)

print("Average Score:", average_score)
print("Most frequent score:", most_frequent)

A4. c) A is true but R is false. Explanation: The assertion is perfectly correct. ceil(4.2) is 5, and floor(4.8) is 4. However, the reason is entirely backwards. ceil() rounds UP (to the ceiling), and floor() rounds DOWN.