When you first start programming in Python, all the code is usually placed in one file. But as projects grow, it becomes necessary to organize the code better and use ready-made solutions. This is where modules and libraries come to the rescue.
What is a module?
A module is simply a file with the extension .py that contains Python code. This can be a set of functions, classes, or variables that you want to use in other programs. Modules help to divide a large program into logical parts and avoid code duplication.
Imagine that you have written a useful function for working with dates. Instead of copying it into each new project, you can save it in a separate file and import it as needed.
How to use the modules?
Let's create a simple module calculator.py:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * bNow we can use these functions in another file:
import calculator
result = calculator.add(5, 3)
print(result) # 8There are several ways to import:
# Import entire module
import calculator
# Import specific functions
from calculator import add, multiply
# Import with alias
import calculator as calc
# Import all (not recommended)
from calculator import *Built-in Python modules
Python comes with a rich standard library — a set of built-in modules that solve many typical tasks. Here are some of the most useful:
math — mathematical functions:
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793random — generation of random numbers:
import random
print(random.randint(1, 10)) # random number from 1 to 10
print(random.choice(['apple', 'banana', 'cherry']))datetime — working with date and time:
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))os — interaction with the operating system:
import os
print(os.getcwd()) # current directory
os.mkdir('new_folder') # create folder
What is a library?
A library is a collection of modules combined to solve certain problems. Libraries can be either built-in or external (third-party). External libraries are created by the developer community and greatly enhance Python's capabilities.
Installing external libraries
To install third-party libraries, use the pip package manager. It is usually installed with Python.
pip install requests
pip install pandas
pip install numpyAfter installation, the library can be imported in the same way as the built-in module:
import requests
response = requests.get('https://api.github.com')
print(response.status_code)Popular libraries for beginners
requests — simple work with HTTP requests:
import requests
response = requests.get('https://api.example.com/data')
data = response.json()BeautifulSoup — HTML and XML parsing:
from bs4 import BeautifulSoup
html = '<html><body><h1>Hello</h1></body></html>'
soup = BeautifulSoup(html, 'html.parser')
print(soup.h1.text) # Hellopandas — data analysis and processing:
import pandas as pd
data = {'name': ['Alice', 'Bob'], 'age': [25, 30]}
df = pd.DataFrame(data)
print(df)Pillow - image processing:
from PIL import Image
img = Image.open('photo.jpg')
img_resized = img.resize((800, 600))
img_resized.save('photo_small.jpg')Creating your own packages
When the project grows, the modules are combined into packages — directories with the __init__.py file. This allows you to create a hierarchical structure:
my_package/
__init__.py
module1.py
module2.py
subpackage/
__init__.py
module3.pyNow you can import like this:
from my_package import module1
from my_package.subpackage import module3Conclusion
Modules and libraries are a powerful tool that makes Python such a popular and versatile language. They allow you not only to structure your own code, but also to use the best practices of thousands of developers around the world. Start by exploring the standard library, then gradually get acquainted with popular external packages. Over time, you will learn how to quickly find the right tools and apply them effectively.
Want to learn Python more deeply and learn how to work professionally with modules and libraries? We invite you to Code — an educational platform where you will master Python from the basics to the advanced level with practical projects and mentors' support.
And we also have a cool Telegram channel with a friendly community where you can ask questions, share successes and find like-minded people.
Join us - it's more interesting to learn together!
