4.3 Concept of Modules, Packages, and Library in Python
Module
A module in Python is a file that contains Python code such as functions, variables, and classes, which can be reused in other programs. A module helps organize code, avoid repetition, and manage large programs by splitting them into smaller files. A Python module is simply a file with the .py extension.
Example — a module file named math_tools.py: def add(a, b): return a + b def subtract(a, b): return a - b
Using this module in another file: import math_tools print(math_tools.add(5, 3)) # 8 print(math_tools.subtract(5, 3)) # 2
A module can also store variables. Example — my_values.py: pi = 3.14159 school_name = "Bright Future School" max_marks = 100
Using it elsewhere: import my_values print("Value of pi:", my_values.pi) print("School Name:", my_values.school_name) print("Maximum Marks:", my_values.max_marks)
The from Keyword
The from keyword is used to import only specific parts (variables, functions, or classes) from a module, instead of the whole module.
Syntax: from module_name import item_name
Example — importing a single item: from math import sqrt print(sqrt(25)) # 5.0 # No need to write math.sqrt(25)
Example — importing multiple items: from my_values import school_name, max_marks print(school_name) print(max_marks)
Example — importing everything (not recommended for large projects): from math import * print(sqrt(16)) print(pi)
Package
A Python package is a collection of related modules grouped together inside a folder (directory). It helps organize a program as it grows and contains many modules. A package requires a special file named __init__.py inside the folder; this file can be empty, but it tells Python that the folder is a package.
Example folder structure: math_operations/ (package folder) __init__.py (initialization file) add_sub.py (module) multiply_divide.py (module)
- 1Create the package folder math_operations.
- 2Inside it, create add_sub.py containing add() and subtract() functions.
- 3Inside it, create multiply_divide.py containing multiply() and divide() functions.
- 4Inside it, create an empty (or minimal) __init__.py file so Python recognizes the folder as a package.
- 5In a separate main program (outside the package folder), import the required modules and use their functions.
Example — using the package: from math_operations import add_sub from math_operations import multiply_divide print("Sum=", add_sub.add(10, 5)) print("Subtraction=", add_sub.subtract(10, 5)) print("Multiply=", multiply_divide.multiply(4, 3)) print("Division=", multiply_divide.divide(10, 2)) # Output: # Sum= 15 # Subtraction= 5 # Multiply= 12 # Division= 5.0
Module vs Package
Diagram showing a single module (.py file) versus a package (a folder containing multiple modules and an __init__.py file).
Common Mistakes (4.3)
- Forgetting to save the module file with a .py extension.
- Forgetting to include the __init__.py file inside a package folder.
- Calling a function from an imported module without the module name prefix, e.g. writing add(5,3) instead of math_tools.add(5,3) when using import module_name.
- Using from module import * carelessly in large programs, which can cause naming conflicts.
SEE Exam Tips (4.3)
- Remember: import module_name requires the module name as a prefix; from module_name import item_name does not.
- Be able to explain, in your own words, the difference between a module and a package.
- Know that a package folder must contain an __init__.py file.
Quick Revision (4.3)
- A module is a single .py file containing reusable code.
- import module_name loads the whole module; from module_name import item loads only a specific part.
- A package is a folder of related modules and must contain an __init__.py file.
- Use dot notation (module_name.function_name) to call a function from an imported module.
SEE Important Areas — Chapter 4 (Part 1)
- Writing and tracing simple programs using variables, operators, and conditional statements.
- for and while loops, including loop control statements (break, continue, else) and nested loops.
- Defining and calling user-defined functions, including all four parameter types.
- The difference between local and global scope, and correct use of the global keyword.
- The difference between mutable and immutable arguments when passed to a function.
- The purpose of the return statement and what a function returns when it has none.
- Dry run (output tracing) of programs involving loops and functions — a very common SEE question type.
- Basic concept of modules, the from keyword, and packages with the __init__.py file.
4.3 Python Libraries
What is a Python Library?
A library is a collection of pre-written functions and modules that can be used to perform specific tasks without writing the code from scratch. It saves time and makes a program more powerful and efficient.
4.3.1 Importing and Use of Standard Libraries
The Standard Library is a collection of built-in modules and packages that come automatically with Python. There are three main ways to import a library.
- 1Import the whole library — brings all functions of the library, but the library name must be used as a prefix. Example: import math then use math.sqrt(16)
- 2Import a specific function — only that function is imported and can be used directly without a prefix. Example: from math import sqrt then use sqrt(64)
- 3Import all functions — imports everything from a library so functions can be used directly, but this is not recommended for large projects because of possible naming confusion. Example: from math import *
Diagram comparing the three ways to import a library in Python: import module, from module import item, and from module import *.
import math print(math.sqrt(16)) # Output: 4.0 from math import sqrt print(sqrt(64)) # Output: 8.0 from math import * print(sqrt(64)) # Output: 8.0 print(factorial(5)) # Output: 120
4.3.2 Introduction to Popular Libraries
Some commonly used Python libraries are Math, Random, Pandas, Turtle, and Matplotlib. Math and random are built-in libraries. Pandas, turtle, and matplotlib may need to be installed first using the command: pip install <library_name>
i) math Library
The math library helps perform mathematical operations like square root, factorial, power, sine, cosine, floor, ceiling, and absolute value.
ii) random Library
The random library is used to generate random numbers, pick random items from a list, or shuffle a list randomly.
iii) pandas Library
Pandas is a third-party Python library used to store, organize, and manage large sets of data in the form of tables called DataFrames. The short alias 'pd' is commonly used when importing pandas.
- To create and display tables (DataFrames)
- To read and write data from files like CSV, Excel, JSON
- To sort, filter, and clean data easily
- To quickly analyze large data sets
import pandas as pd data = {"Names": ["Ram", "Sita"], "Marks": [85, 90]} df = pd.DataFrame(data) print(df)
iv) Turtle Library
Turtle is a standard Python library used for creating simple graphics and drawings using a virtual 'turtle' cursor that leaves a trail as it moves, like a pen drawing on paper. It is used for learning programming concepts visually, drawing shapes and patterns, creating simple animations, and making creative art projects.
v) matplotlib Library
Matplotlib is a powerful third-party Python library used for making 2D graphs and plots such as line graphs, bar charts, pie charts, scatter plots, and histograms. It helps visualize data to understand trends and patterns easily.
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] plt.plot(x, y) plt.title("Simple Line Graph") plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.show()
4.4 Graphics Using Turtle
Graphics using turtle in Python means creating drawings, shapes, patterns, and designs on the screen by controlling a virtual pen (the turtle) through programming commands.
Steps to Draw Turtle in Python
- 1Import the turtle library
- 2Create a turtle object using the Turtle() function
- 3Use turtle's functions to move and draw
- 4Use turtle.done() to finish the program
import turtle t = turtle.Turtle() t.forward(100) t.left(90) t.forward(100) turtle.done()
Drawing a Filled Shape
import turtle t = turtle.Turtle() t.fillcolor("red") t.begin_fill() for _ in range(4): t.forward(100) t.left(90) t.end_fill() turtle.done()
Example output of Turtle graphics code: a filled colored square drawn on screen by the turtle cursor.