⚡0 XP🔥0

Modules, Packages & pip

Lesson 23 of 33 ⏱ 7 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs Python

Import and use modules (math, random, datetime, collections, os), create your own module, understand packages, __name__ == "__main__", and install libraries with pip.

What is a module?#

A module is simply a Python file (.py) containing functions, variables and classes that you can reuse in other programs by importing it.

Python comes with a huge standard library - hundreds of ready modules for maths, dates, files, random numbers, internet, and more. ("Batteries included" is Python's motto.)

Ways to import#

▶ Try it YourselfPython
Ctrl + Enter to run
Style Use like When
import math math.sqrt(9) clear where each name comes from (recommended)
from math import sqrt sqrt(9) you use a few names often
import numpy as np np.array(...) long module names - common conventions
from math import * sqrt(9) avoid - pollutes your namespace, hides where names come from
हिंदी में समझें

Module = पहले से लिखे हुए code की एक file, जिसे आप import करके इस्तेमाल कर सकते हैं - जैसे औज़ारों का डिब्बा (toolbox)।

  • import math → पूरा toolbox ले आओ, और हर औज़ार math. लगाकर इस्तेमाल करो (math.sqrt(16))।
  • from math import sqrt → toolbox से सिर्फ एक औज़ार निकाल लो, और सीधे sqrt(16) लिखो।
  • import pandas as pd → लंबे नाम को छोटा नाम (alias) दे दो।

Useful standard library modules#

math#

▶ Try it YourselfPython
Ctrl + Enter to run

random#

▶ Try it YourselfPython
Ctrl + Enter to run

Run it several times - the output changes each time.

datetime#

▶ Try it YourselfPython
Ctrl + Enter to run

Common format codes: %d day, %m month, %Y 4-digit year, %H hour (24h), %M minute, %A weekday name, %B month name.

collections#

▶ Try it YourselfPython
Ctrl + Enter to run

os and sys (working with the system)#

import os
print(os.getcwd())               # current folder
print(os.listdir("."))           # files in a folder
os.makedirs("reports", exist_ok=True)
print(os.path.exists("data.csv"))

import sys
print(sys.version)               # Python version

Others worth knowing#

Module Used for
json read/write JSON data (APIs, config files)
csv read/write CSV (Excel-like) files
time delays (time.sleep(2)), timing code
statistics mean, median, mode, stdev
re regular expressions (pattern matching in text)
pathlib modern file path handling
▶ Try it YourselfPython
Ctrl + Enter to run

Exploring a module#

import math
print(dir(math))        # list everything inside
help(math.sqrt)         # documentation for one function

Creating your own module#

Any .py file is a module. Suppose you create billing.py:

# billing.py
GST_RATE = 18

def add_gst(amount):
    return amount + amount * GST_RATE / 100

def format_rupees(amount):
    return f"Rs. {amount:,.2f}"

In another file in the same folder, e.g. main.py:

import billing

total = billing.add_gst(2500)
print(billing.format_rupees(total))     # Rs. 2,950.00

if name == "main":#

Every module has a built-in variable __name__:

  • When you run the file directly → __name__ is "__main__".
  • When the file is imported → __name__ is the module's name ("billing").

This lets a file contain test code that runs only when executed directly:

# billing.py
def add_gst(amount):
    return amount * 1.18

if __name__ == "__main__":
    # runs for: python billing.py
    # does NOT run for: import billing
    print(add_gst(100))
हिंदी में समझें

if __name__ == "__main__": का मतलब है - "यह code तभी चलाओ जब यह file सीधे चलाई जाए, किसी दूसरी file में import होने पर नहीं।"

इससे आप एक ही file में functions भी रख सकते हैं और उनकी testing भी कर सकते हैं - import करने वाले program पर testing वाला code असर नहीं डालेगा। Professional Python code में यह लाइन लगभग हर main file में दिखती है।

Packages#

A package is a folder of modules. It usually contains an __init__.py file:

myshop/
├── __init__.py
├── billing.py
└── inventory.py
from myshop import billing
from myshop.inventory import check_stock

pip - installing third-party libraries#

Beyond the standard library, there are 500,000+ free packages on PyPI (pypi.org). Install them with pip in your terminal (not inside Python):

pip install requests          # install
pip install pandas==2.2.2     # a specific version
pip list                      # what's installed
pip uninstall requests        # remove
pip freeze > requirements.txt # save your project's packages
pip install -r requirements.txt   # install them on another computer

Popular packages:

Package Purpose
requests call websites and APIs
pandas data analysis, Excel/CSV
numpy fast maths on arrays
matplotlib charts
flask, django, fastapi web development
openpyxl Excel files
selenium browser automation
Tip

Use a virtual environment for each project so package versions don't clash:

python -m venv venv
venv\Scripts\activate        # Windows
source venv/bin/activate     # macOS / Linux
pip install requests
Did you know?

The browser editor on this site runs a special build of Python (Pyodide). The standard library works, but pip install is not available here - practise pip on your own computer.

Summary#

  • A module is a .py file; import with import x, from x import y, or import x as z.
  • The standard library includes math, random, datetime, collections, os, json, csv and more.
  • Your own .py files are modules too; packages are folders of modules.
  • if __name__ == "__main__": runs code only when the file is executed directly.
  • Install third-party packages with pip install name, ideally inside a virtual environment.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Hypotenuse

Using the math module, write hypotenuse(a, b) that returns √(a² + b²) rounded to 2 decimals.

2

Most common words

Use collections.Counter to print the two most common words in the sentence as a list of (word, count) tuples.

Expected output:
[('blue', 4), ('red', 3)]
3

Days until an event

Using datetime.date, write days_between(d1, d2) that returns the number of days from date d1 to date d2. Both are given as strings "YYYY-MM-DD".

Quick Quiz

Q1.

Which import lets you write sqrt(16) directly?

Q2.

What is a module in Python?

Q3.

What is __name__ when a file is run directly (python file.py)?

Q4.

Which command installs the requests library?

Q5.

What does import pandas as pd do?