Python Programming for Beginners

Chapter 13 Python Modules and Packages – Importing and Using Modules

<h2>13.1 Introduction to Python Modules</h2>

<p>
A module is a Python file that contains code such as functions, variables,
classes, and other definitions. Modules help organize programs into
smaller and reusable parts.
</p>

<p>
Instead of writing the same code repeatedly, you can place useful code
inside a module and import it whenever you need it.
</p>

<pre><code>import math

print(math.sqrt(25))</code></pre>

<p>Output:</p>

<pre><code>5.0</code></pre>


<h2>13.2 Why Use Modules?</h2>

<p>
Modules make Python programs easier to organize, maintain, test, and
reuse. They are especially useful when a program becomes large.
</p>

<ul>
   <li>Reuse existing code</li>
   <li>Organize large programs</li>
   <li>Reduce duplicate code</li>
   <li>Make programs easier to maintain</li>
   <li>Use functionality provided by Python libraries</li>
</ul>


<h2>13.3 Importing a Module</h2>

<p>
The <code>import</code> statement is used to load a module into a Python
program.
</p>

<pre><code>import math

print(math.pi)</code></pre>

<p>Output:</p>

<pre><code>3.141592653589793</code></pre>


<h2>13.4 Using Functions from a Module</h2>

<p>
After importing a module, you can access its functions using the module
name followed by a dot.
</p>

<pre><code>import math

number = 16

result = math.sqrt(number)

print(result)</code></pre>

<p>Output:</p>

<pre><code>4.0</code></pre>


<h2>13.5 The math Module</h2>

<p>
The <code>math</code> module provides many mathematical functions and
constants.
</p>

<pre><code>import math

print(math.sqrt(49))
print(math.pow(2, 3))
print(math.ceil(4.2))
print(math.floor(4.8))</code></pre>

<p>Output:</p>

<pre><code>7.0
8.0
5
4</code></pre>


<h2>13.6 Mathematical Constants</h2>

<p>
The <code>math</code> module provides useful constants such as
<code>pi</code> and <code>e</code>.
</p>

<pre><code>import math

print("Pi:", math.pi)
print("Euler's number:", math.e)</code></pre>


<h2>13.7 The random Module</h2>

<p>
The <code>random</code> module provides functions for generating
pseudo-random values.
</p>

<pre><code>import random

number = random.randint(1, 10)

print(number)</code></pre>

<p>
The result can be different each time the program runs.
</p>


<h2>13.8 Generating a Random Number</h2>

<p>
The <code>randint()</code> function returns a random integer between
the specified limits, including both limits.
</p>

<pre><code>import random

number = random.randint(1, 100)

print("Random number:", number)</code></pre>


<h2>13.9 Choosing a Random Item</h2>

<p>
The <code>choice()</code> function selects one item randomly from a
sequence.
</p>

<pre><code>import random

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

fruit = random.choice(fruits)

print("Selected fruit:", fruit)</code></pre>


<h2>13.10 The datetime Module</h2>

<p>
The <code>datetime</code> module provides classes and functions for
working with dates and times.
</p>

<pre><code>import datetime

today = datetime.date.today()

print(today)</code></pre>


<h2>13.11 Getting the Current Date and Time</h2>

<pre><code>import datetime

now = datetime.datetime.now()

print(now)</code></pre>


<h2>13.12 Getting the Current Year</h2>

<pre><code>import datetime

today = datetime.date.today()

print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)</code></pre>


<h2>13.13 Importing a Specific Function</h2>

<p>
Instead of importing the complete module, you can import a specific
function using <code>from</code>.
</p>

<pre><code>from math import sqrt

print(sqrt(64))</code></pre>

<p>Output:</p>

<pre><code>8.0</code></pre>


<h2>13.14 Importing Multiple Functions</h2>

<pre><code>from math import sqrt, ceil, floor

print(sqrt(81))
print(ceil(4.2))
print(floor(4.8))</code></pre>


<h2>13.15 Importing Everything from a Module</h2>

<p>
Python allows importing all names from a module using the asterisk
symbol. However, this approach is generally less clear in larger
programs because it can make it difficult to identify where a name
came from.
</p>

<pre><code>from math import *

print(sqrt(100))
print(pi)</code></pre>


<h2>13.16 Using an Alias for a Module</h2>

<p>
The <code>as</code> keyword can be used to give a module a shorter alias.
</p>

<pre><code>import math as m

print(m.sqrt(144))
print(m.pi)</code></pre>

<p>Output:</p>

<pre><code>12.0
3.141592653589793</code></pre>


<h2>13.17 Using an Alias for a Function</h2>

<pre><code>from math import sqrt as square_root

print(square_root(121))</code></pre>

<p>Output:</p>

<pre><code>11.0</code></pre>


<h2>13.18 Creating Your Own Module</h2>

<p>
You can create your own module by saving Python code in a file with
the <code>.py</code> extension.
</p>

<p>
For example, create a file named <code>calculator.py</code>.
</p>

<pre><code>def add(a, b):
   return a + b


def subtract(a, b):
   return a - b</code></pre>


<h2>13.19 Importing Your Own Module</h2>

<p>
Suppose <code>calculator.py</code> and your main Python file are in the
same folder.
</p>

<pre><code>import calculator

print(calculator.add(10, 5))
print(calculator.subtract(10, 5))</code></pre>

<p>Output:</p>

<pre><code>15
5</code></pre>


<h2>13.20 Importing Functions from Your Module</h2>

<pre><code>from calculator import add

result = add(20, 30)

print(result)</code></pre>

<p>Output:</p>

<pre><code>50</code></pre>


<h2>13.21 Creating a Utility Module</h2>

<p>
A utility module can contain commonly used functions.
</p>

<pre><code># utility.py

def square(number):
   return number * number


def cube(number):
   return number * number * number


def is_even(number):
   return number % 2 == 0</code></pre>


<h2>13.22 Using the Utility Module</h2>

<pre><code>import utility

print(utility.square(5))
print(utility.cube(3))
print(utility.is_even(10))</code></pre>

<p>Output:</p>

<pre><code>25
27
True</code></pre>


<h2>13.23 The __name__ Variable</h2>

<p>
Every Python module has a special variable called
<code>__name__</code>. When a file is executed directly,
<code>__name__</code> is set to <code>"__main__"</code>.
</p>

<pre><code>print(__name__)</code></pre>

<p>
When the file is run directly, the output is:
</p>

<pre><code>__main__</code></pre>


<h2>13.24 Using if __name__ == "__main__"</h2>

<p>
The <code>if __name__ == "__main__"</code> pattern allows code to run
only when the file is executed directly, rather than when it is imported
as a module.
</p>

<pre><code>def greet():
   print("Hello from Python")


if __name__ == "__main__":
   greet()</code></pre>


<h2>13.25 Module Variables</h2>

<p>
A module can contain variables as well as functions.
</p>

<pre><code># student.py

name = "Aman"
age = 16

def show_student():
   print(name)
   print(age)</code></pre>


<h2>13.26 Accessing Module Variables</h2>

<pre><code>import student

print(student.name)
print(student.age)

student.show_student()</code></pre>


<h2>13.27 Standard Library Modules</h2>

<p>
Python includes a large standard library containing modules for many
common programming tasks.
</p>

<table>
   <thead>
       <tr>
           <th>Module</th>
           <th>Common Use</th>
       </tr>
   </thead>
   <tbody>
       <tr>
           <td><code>math</code></td>
           <td>Mathematical operations</td>
       </tr>
       <tr>
           <td><code>random</code></td>
           <td>Random values</td>
       </tr>
       <tr>
           <td><code>datetime</code></td>
           <td>Dates and times</td>
       </tr>
       <tr>
           <td><code>os</code></td>
           <td>Operating system interaction</td>
       </tr>
       <tr>
           <td><code>sys</code></td>
           <td>Python runtime information</td>
       </tr>
       <tr>
           <td><code>json</code></td>
           <td>Working with JSON data</td>
       </tr>
       <tr>
           <td><code>statistics</code></td>
           <td>Basic statistical calculations</td>
       </tr>
   </tbody>
</table>


<h2>13.28 The os Module</h2>

<p>
The <code>os</code> module provides functions for interacting with the
operating system.
</p>

<pre><code>import os

print(os.getcwd())</code></pre>

<p>
The <code>getcwd()</code> function returns the current working directory.
</p>


<h2>13.29 Creating a Folder with os</h2>

<pre><code>import os

folder = "practice"

if not os.path.exists(folder):
   os.mkdir(folder)

print("Folder checked.")</code></pre>


<h2>13.30 The sys Module</h2>

<p>
The <code>sys</code> module provides access to information and features
related to the Python runtime environment.
</p>

<pre><code>import sys

print(sys.version)</code></pre>


<h2>13.31 The statistics Module</h2>

<p>
The <code>statistics</code> module provides functions for common
statistical calculations.
</p>

<pre><code>import statistics

marks = [70, 80, 90, 85, 75]

print(statistics.mean(marks))
print(statistics.median(marks))</code></pre>

<p>Output:</p>

<pre><code>80
80</code></pre>


<h2>13.32 Working with JSON</h2>

<p>
The <code>json</code> module is useful when working with data stored
in JSON format.
</p>

<pre><code>import json

student = {
   "name": "Aman",
   "age": 16,
   "marks": 88
}

data = json.dumps(student)

print(data)</code></pre>

<p>Output:</p>

<pre><code>{"name": "Aman", "age": 16, "marks": 88}</code></pre>


<h2>13.33 Converting JSON Back to Python Data</h2>

<pre><code>import json

data = '{"name": "Aman", "age": 16}'

student = json.loads(data)

print(student["name"])
print(student["age"])</code></pre>

<p>Output:</p>

<pre><code>Aman
16</code></pre>


<h2>13.34 What is a Package?</h2>

<p>
A package is a way of organizing related Python modules into a directory
structure. Packages are useful for large projects containing many
modules.
</p>

<p>
For example, a project might contain the following structure:
</p>

<pre><code>myproject/
   main.py
   tools/
       calculator.py
       converter.py
       validator.py</code></pre>


<h2>13.35 Importing from a Package</h2>

<p>
A module inside a package can be imported using the package name.
</p>

<pre><code>from tools import calculator

result = calculator.add(10, 20)

print(result)</code></pre>


<h2>13.36 Package Organization</h2>

<p>
Packages help divide a large application into logical sections.
For example, an educational application could be organized like this:
</p>

<pre><code>education/
   students/
       records.py
       attendance.py
   courses/
       subjects.py
       lessons.py
   exams/
       questions.py
       results.py</code></pre>


<h2>13.37 Module Reusability</h2>

<p>
One of the biggest advantages of modules is code reuse. A function
written once can be imported and used in multiple programs.
</p>

<pre><code># calculator.py

def multiply(a, b):
   return a * b</code></pre>

<p>Another program can use it:</p>

<pre><code>from calculator import multiply

print(multiply(8, 7))</code></pre>

<p>Output:</p>

<pre><code>56</code></pre>


<h2>13.38 Handling Import Errors</h2>

<p>
If Python cannot find the requested module, it may raise a
<code>ModuleNotFoundError</code>.
</p>

<pre><code>try:
   import unknown_module
except ModuleNotFoundError:
   print("Module was not found.")</code></pre>

<p>Output:</p>

<pre><code>Module was not found.</code></pre>


<h2>13.39 Module Naming</h2>

<p>
Choose clear and meaningful names for your own modules. Avoid names
that conflict with important Python modules or commonly installed
packages.
</p>

<pre><code>calculator.py
student.py
converter.py
database_helper.py</code></pre>


<h2>13.40 Example: Calculator Module</h2>

<p>
Create a file called <code>calculator.py</code>.
</p>

<pre><code>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):
   if b == 0:
       return "Cannot divide by zero"
   return a / b</code></pre>


<h2>13.41 Using the Calculator Module</h2>

<pre><code>import calculator

print("Addition:", calculator.add(10, 5))
print("Subtraction:", calculator.subtract(10, 5))
print("Multiplication:", calculator.multiply(10, 5))
print("Division:", calculator.divide(10, 5))</code></pre>

<p>Output:</p>

<pre><code>Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0</code></pre>


<h2>13.42 Example: Random Password Character</h2>

<pre><code>import random

characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

character = random.choice(characters)

print("Selected character:", character)</code></pre>


<h2>13.43 Example: Random Password Generator</h2>

<pre><code>import random

characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

password = ""

for i in range(8):
   password += random.choice(characters)

print("Generated password:", password)</code></pre>

<p>
This example demonstrates how modules can be combined with loops and
strings to build a small practical program.
</p>


<h2>13.44 Example: Date Information</h2>

<pre><code>import datetime

today = datetime.date.today()

print("Today:", today)
print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)</code></pre>


<h2>13.45 Example: Mathematical Calculator</h2>

<pre><code>import math

number = float(input("Enter a number: "))

print("Square root:", math.sqrt(number))
print("Square:", math.pow(number, 2))
print("Ceiling:", math.ceil(number))
print("Floor:", math.floor(number))</code></pre>


<h2>13.46 Module vs Package</h2>

<table>
   <thead>
       <tr>
           <th>Feature</th>
           <th>Module</th>
           <th>Package</th>
       </tr>
   </thead>
   <tbody>
       <tr>
           <td>Basic Structure</td>
           <td>Usually a Python file</td>
           <td>Directory containing related modules</td>
       </tr>
       <tr>
           <td>Purpose</td>
           <td>Organizes reusable code</td>
           <td>Organizes multiple related modules</td>
       </tr>
       <tr>
           <td>Example</td>
           <td><code>calculator.py</code></td>
           <td><code>tools/</code></td>
       </tr>
   </tbody>
</table>


<h2>13.47 Important Python Import Statements</h2>

<table>
   <thead>
       <tr>
           <th>Statement</th>
           <th>Purpose</th>
       </tr>
   </thead>
   <tbody>
       <tr>
           <td><code>import math</code></td>
           <td>Imports the complete module</td>
       </tr>
       <tr>
           <td><code>from math import sqrt</code></td>
           <td>Imports a specific function</td>
       </tr>
       <tr>
           <td><code>import math as m</code></td>
           <td>Creates an alias for a module</td>
       </tr>
       <tr>
           <td><code>from math import sqrt as root</code></td>
           <td>Creates an alias for a function</td>
       </tr>
   </tbody>
</table>


<h2>13.48 Best Practices for Using Modules</h2>

<ul>
   <li>Give modules clear and meaningful names.</li>
   <li>Keep related functions together.</li>
   <li>Avoid unnecessarily large modules.</li>
   <li>Prefer explicit imports when they improve readability.</li>
   <li>Use aliases only when they make code easier to understand.</li>
   <li>Avoid unnecessary duplicate code.</li>
   <li>Keep reusable functionality separate from application code.</li>
</ul>


<h2>13.49 Chapter Summary</h2>

<p>
In this chapter, you learned how Python modules and packages help
organize and reuse code.
</p>

<ul>
   <li>What a Python module is</li>
   <li>Why modules are useful</li>
   <li>How to import modules</li>
   <li>How to import specific functions</li>
   <li>How to use aliases</li>
   <li>How to create your own modules</li>
   <li>How to create reusable functions inside modules</li>
   <li>The purpose of <code>__name__</code></li>
   <li>The use of <code>if __name__ == "__main__"</code></li>
   <li>Common Python standard-library modules</li>
   <li>What packages are</li>
   <li>How modules and packages are organized</li>
</ul>


<h2>13.50 Quick Revision Questions</h2>

<ol>
   <li>What is a Python module?</li>
   <li>Why are modules useful?</li>
   <li>Which keyword is used to import a module?</li>
   <li>How can you import a specific function from a module?</li>
   <li>What is a module alias?</li>
   <li>What is the purpose of the math module?</li>
   <li>What is the random module used for?</li>
   <li>What is the purpose of the datetime module?</li>
   <li>What is a Python package?</li>
   <li>What is the purpose of __name__?</li>
</ol>


<h2>13.51 Practice Exercises</h2>

<ol>
   <li>Import the math module and calculate the square root of a number.</li>
   <li>Generate a random number between 1 and 100.</li>
   <li>Create a module containing addition and subtraction functions.</li>
   <li>Import your module into another Python program.</li>
   <li>Create a module containing functions for calculating area.</li>
   <li>Use the datetime module to display today's date.</li>
   <li>Create a small random password generator.</li>
   <li>Create a utility module containing square and cube functions.</li>
   <li>Create a package containing two related Python modules.</li>
   <li>Use the statistics module to calculate the average of student marks.</li>
</ol>


<h2>13.52 Mini Project: Utility Module</h2>

<p>
Create a reusable utility module containing functions for common
calculations.
</p>

<pre><code># utility.py

def square(number):
   return number * number


def cube(number):
   return number * number * number


def is_even(number):
   return number % 2 == 0</code></pre>

<p>
Now import the module into another Python file.
</p>

<pre><code>import utility

number = 6

print("Square:", utility.square(number))
print("Cube:", utility.cube(number))
print("Even:", utility.is_even(number))</code></pre>

<p>Output:</p>

<pre><code>Square: 36
Cube: 216
Even: True</code></pre>


<h2>What's Next?</h2>

<p>
<strong>
Next Chapter: Python File Handling – Creating, Reading, Writing,
Appending and Managing Files
</strong>
</p>