Keep your place in this quest

Log in or sign up for free to subscribe, follow lesson progress, and access more learning content.

Now that we’ve learned what modules and packages are, let’s see the different ways we can bring them into our programs.

Remember:

  • A module is a single Python file (.py) containing code you can reuse.
  • A package is a collection of related modules in a folder with an __init__.py file.

The main goal of importing is to organize code and make it easy to reuse without copying and pasting.


Importing an Entire Package or Module

The most common way to import is with the import keyword.
Example — importing Python’s built-in math module:

import math

Once imported, you access its features using the syntax:

module_name.function_name()

Example:

print(math.sqrt(25))  # returns 5.0

Here, math.sqrt() means “use the sqrt function from the math module”.

TIP: This approach keeps your code clear because it shows exactly where each function came from.

Importing a Specific Function or Variable

You can also import just what you need from a module using from ... import ....

Example — importing only the sqrt function:

from math import sqrt

print(sqrt(25))  # returns 5.0

Now we can call sqrt() directly without writing math. in front of it.

Note: This can make code shorter, but if you import too many things this way, it’s harder to see where each function comes from.

Importing Everything from a Module (Not Recommended)

You can import all functions and variables from a module at once using *:

from math import *
print(sqrt(25))  # returns 5.0

Why this is discouraged:

  • It can overwrite existing variables or functions without warning.
  • It makes it unclear which module a function came from.
  • It can slow down your program if the module is large.

IMPORTANT!: Avoid from module import * unless you have a very good reason and you control all the code.


Importing with an Alias

Sometimes a module’s name is long or used very often in your code. You can give it a shorter alias using as.

Example — importing NumPy with the alias np:

import numpy as np

x = np.array([1, 2, 3])

Now you can call NumPy functions with np. instead of numpy.. This is a common convention in the Python community.


Summary of Import Styles

  • import module — Clear and explicit; use full name each time.
  • from module import function — Shorter calls, but less explicit.
  • from module import * — Avoid unless absolutely necessary.
  • import module as alias — Shortens long names while keeping clarity.

In the next lesson, we’ll move on to file handling — reading and writing data to files so your programs can remember information even after they stop running.