Using Python Libraries

Using Python Libraries

4.2 What is a Library?

A Library is a collection of modules and packages that together provide specific functionality. Think of it as a pre-built toolkit so you don’t have to “reinvent the wheel.”

  • Standard Library: Comes pre-installed with Python (e.g., math, statistics).
  • External Libraries: Need to be installed via pip (e.g., numpy, pandas).

4.2.1 What is a Module?

A Module is a single file (with a .py extension) containing Python definitions and statements—functions, classes, and variables.


4.3 Importing Modules

To use a module’s contents, you must first bring it into your current program using the import statement.

4.3.1 Importing Entire Module

This imports everything and requires the module name as a prefix to access its functions.

import math
print(math.sqrt(16))  # Syntax: module_name.function_name()

4.3.2 Importing Select Objects

This allows you to use specific functions directly without the module prefix.

from math import sqrt, pi
print(sqrt(25))  # Directly calls the function

Note: Using from module import * is generally discouraged as it can lead to name conflicts between different modules.

4.3.3 How Python Processes import

When you run an import command, Python performs three main steps:

  1. Search: It looks for the file in the current directory and directories listed in sys.path.
  2. Compile: It compiles the source code into byte code (.pyc).
  3. Execute: It runs the code in the module to initialize its objects.

4.4 Python Standard Library

Python provides many built-in tools that are ready to use immediately.

4.4.1 Built-in Functions

These are always available without any import statement.

  • type(): Returns the data type.
  • len(): Returns the length of an object.
  • range(): Generates a sequence of numbers.
  • input() and print(): For I/O operations.

4.4.2 Working with Standard Modules

ModulePurposeCommon Functions
mathMathematical constants/functionsceil(), floor(), pow(), sin()
randomRandom number generationrandom(), randint(), randrange()
statisticsMathematical statisticsmean(), median(), mode()

4.5 Creating a Python Library (Packages)

A Package is essentially a directory containing multiple modules and a special file named __init__.py.

4.5.1 Structure of a Package

A typical package hierarchy looks like this:

MyPackage/
├── __init__.py      (Must Required)
├── module1.py       (Contains functions/classes)
└── module2.py

__init__.py is must required to treat directory as a package.

4.5.2 Procedure for Creating Packages

  1. Create a Folder: Name it after your package.
  2. Add Modules: Place your .py files inside.
  3. Add __init__.py: This file can be empty, but it must exist for Python to recognize the folder as a package.

4.5.3 Using/Importing your Library

Once created, you can access your custom code using dot notation:

import MyPackage.module1
# OR
from MyPackage import module1

Example to create a Python package:

To create and use a Python package, you need a specific directory structure. A package is essentially a folder containing an __init__.py file and one or more module files.

Here is a step-by-step example:

1. Create the Structure

Imagine we are creating a package called Geometry that helps calculate the area of shapes.

Step A: Create a folder named Geometry.

Step B: Inside that folder, create two files:

  • __init__.py: (Leave this empty; it tells Python this folder is a package).
  • area.py: (This is our module).

2. Write the Module Code (area.py)

Inside Geometry/area.py, write a simple function:

Python

# Geometry/area.py

def rectangle(length, breadth):
    return length * breadth

def circle(radius):
    return 3.14 * (radius ** 2)

3. Import and Use the Package

Now, create a new script (e.g., main.py) outside the Geometry folder to use your package.

Method A: Using the module prefix

Python

import Geometry.area

# Usage: package.module.function()
result = Geometry.area.rectangle(10, 5)
print("Area of Rectangle:", result)

Method B: Using from for direct access (Recommended for Class 12)

Python

from Geometry import area

# Usage: module.function()
print("Area of Circle:", area.circle(7))

Method C: Importing a specific function

Python

from Geometry.area import rectangle

# Usage: function()
print("Direct Rectangle Area:", rectangle(4, 3))

Important Exam Note:

  • __init__.py is the “Passport” of the folder. Without it, Python versions older than 3.3 won’t recognize the folder as a package, and even in newer versions, it is standard practice to include it.
  • When importing, we use the Dot (.) operator to navigate from the Package to the Module.

Quick Tip for Exams:

Always remember that randint(a, b) in the random module includes both endpoints a and b, whereas randrange(a, b) excludes the upper limit b. This is a very common trick question!

Practice Questions


Problem 1: String Slicing with Random

Code:

Python

import random
STR = "PYTHON"
START = random.randint(0, 1)
END = random.randrange(3, 5)

print(STR[START:END])

Questions:

  1. What are the possible values for START and END?
  2. Out of the following, which are the possible outputs?
    • i. PYTH
    • ii. YTH
    • iii. YTHO
    • iv. PYTHON

Solution:

  1. START: 0 or 1. END: 3 or 4.
  2. Possible Outputs:
    • i (PYTH): If START=0, END=4 → STR[0:4]
    • ii (YTH): If START=1, END=4 → STR[1:4]
    • iii (YTHO): Not possible (Index 4 is ‘O’, but STR[1:4] only goes up to index 3).
    • iv (PYTHON): Not possible (Length is too short).

Problem 2: List Indexing & Step

Code:

Python

import random
VAL = [10, 20, 30, 40, 50, 60]
GO = random.randint(2, 4)

for I in range(0, GO, 2):
    print(VAL[I], end="!")

Questions:

  1. What is the maximum number of times the loop can execute?
  2. State the possible outputs from the following:
    • i. 10!30!50!
    • ii. 10!30!
    • iii. 10!
    • iv. 20!40!

Solution:

  1. Max executions: 2 times (If GO is 3 or 4, range(0, 3, 2) and range(0, 4, 2) both yield indices 0 and 2).
  2. Possible Outputs:
    • ii (10!30!): Occurs if GO is 3 or 4.
    • iii (10!): Occurs if GO is 2 (range(0, 2, 2) only yields index 0).

Problem 3: Random Range & Math Offset

Code:

Python

import random
MY_NUMS = [11, 22, 33, 44, 55]
SHIFT = random.randint(0, 2)

for J in range(SHIFT, SHIFT + 2):
    print(MY_NUMS[J] + 5, end="#")

Questions:

  1. What is the minimum and maximum value that can be printed in this sequence?
  2. Which of these outputs is valid?
    • a. 16#27#
    • b. 38#49#
    • c. 22#33#
    • d. 11#22#

Solution:

  1. Min: 16 (11+5). Max: 49 (44+5).
  2. Valid Outputs:
    • a (16#27#): If SHIFT=0, indices are 0, 1. (11+5, 22+5).
    • b (38#49#): If SHIFT=2, indices are 2, 3. (33+5, 44+5).

Problem 4: Nested Random logic

Code:

Python

import random
COLOR = ["RED", "GREEN", "BLUE"]
PICK = random.randrange(1, 3) # Note the range!

for C in range(PICK):
    print(COLOR[C], end="*")

Question:

Find the possible outputs from the list below and justify your answer:

  1. RED*
  2. REDGREEN
  3. REDGREENBLUE*
  4. GREEN*

Solution:

  • PICK can be 1 or 2 (as 3 is excluded in randrange).
  • If PICK is 1, range(1) gives index 0. Output: RED*
  • If PICK is 2, range(2) gives indices 0 and 1. Output: REDGREEN
  • Justification: The loop always starts at index 0 and PICK can never be 3, so BLUE can never be reached. GREEN* alone is impossible because the loop starts from index 0 (RED).

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top