Categories

Chapter 3.3: Importing Modules and Using Standard Libraries

Python comes with a vast standard library, a collection of modules that provides implementations of commonly used functionalities. Besides these, there are numerous third-party modules available, providing even more capabilities.

What is a Module?

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py added. We define functions, classes, and variables in a module, and we can also include runnable code.

How to Import a Module?

To use any module in your Python code, you must first import it. Importing a module essentially means loading it into memory and making its functionalities accessible to your code. Here’s the basic syntax for importing a module:

import module_name

For example, to import the built-in math module, you would write:

import math

Now you can use functions from the math module, like math.sqrt to calculate the square root of a number:

import math

print(math.sqrt(25))  # prints: 5.0

Importing Specific Items from a Module

To import a specific function or variable from a module, you can use the from keyword:

from module_name import item_name

For example, to import only the sqrt function from the math module, you would write:

from math import sqrt

print(sqrt(25))  # prints: 5.0

Renaming a Module at Import

You can rename a module when importing it by using the as keyword. This is commonly done for modules with longer names:

import module_name as alias

For example, the numpy module is often aliased as np:

import numpy as np

print(np.sqrt(25))  # prints: 5.0

Python Standard Library

Python’s standard library is a collection of modules that provides access to operations that aren’t part of the core Python language but are included in every Python installation. It includes modules for file I/O, system calls, string management, internet protocols, and more.

For example, here’s how you might use the random module from the standard library to generate a random number:

import random

print(random.randint(1, 10))  # prints: a random integer between 1 and 10

In conclusion, modules and libraries are what make Python a powerful and versatile language. By importing and utilizing different modules, you can vastly extend Python’s capabilities without having to write a lot of code yourself.

Leave a Reply

Your email address will not be published. Required fields are marked *