DEV Community

Kajiru
Kajiru

Posted on

Getting Started with Python (Part 11): Using Modules

Using Modules

In this article, you’ll learn about modules in Python.


What Is a Module?

A module is a separate file (program) that contains Python code.

By importing and combining various modules, you can build applications more efficiently.

In Python, files that you create yourself can also be used as modules.

In addition, Python provides many built-in standard modules.

Modules developed by third parties are called third-party modules.


Importing a Module

You can import a module using the import statement.

import module_name
Enter fullscreen mode Exit fullscreen mode

Here, let’s try using one of Python’s standard modules, random.

As the name suggests, it is used to generate random values.

import random

# Random float between 0.0 and 1.0
print(random.random())  # 0.8189799827412905

# Random integer between 1 and 10
print(random.randint(1, 10))  # 2
Enter fullscreen mode Exit fullscreen mode

Importing a Specific Part of a Module

By using from, you can import only a specific part of a module.

In the following example, we import only the random function from the random module.

from random import random

# Only the random function is imported
print(random())  # 0.38405708986017906
Enter fullscreen mode Exit fullscreen mode

Giving a Module an Alias

By using as, you can give an imported module or function an alias.

This is useful to avoid name conflicts with other modules.

from random import random as r

# It doesn’t get much shorter than this!
print(r())  # 0.941147291147711
Enter fullscreen mode Exit fullscreen mode

Commonly Used Standard Modules

Here are some commonly used standard modules in Python.

Module Purpose Example Description
os OS operations os.listdir(".") Get a list of files in the current directory
pathlib File paths Path("test.txt").exists() Check if a file exists
time Time control time.sleep(1) Wait for 1 second
datetime Date and time datetime.datetime.now() Get the current date and time
random Random numbers random.random() Float between 0.0 and 1.0
math Math functions math.sqrt(9) Square root (3.0)

Popular Third-Party Modules

Next, let’s look at some popular third-party modules.

To use these modules, you need to install them separately using pip.

Module Use Case Popularity
numpy Fast numerical computation, arrays ★★★★★
pandas Data analysis, tabular data processing ★★★★★
matplotlib Data visualization, plotting ★★★★★
django, flask, fastapi Web apps and APIs ★★★★★
requests Web API calls, HTTP communication ★★★★★
sqlalchemy Database operations ★★★★★
beautifulsoup Web scraping ★★★★★
Pillow Image editing and processing ★★★★★
scikit-learn, xgboost, catboost Machine learning ★★★★★

What’s Next?

Thank you for reading!

In the next article, we’ll learn about classes.

The next title will be:

“Getting Started with Python (Part 9): Using Classes”

Stay tuned! 🚀

Top comments (0)