CodingNic

Modules, Packages, and Virtual Environments

Importing Modules

Modules, Packages, and Virtual Environments 26 min read

Importing Modules

Importing Modules

A module is useful when you can use its code in another file.

Python uses import for this.

What Does Import Mean?

Import means bringing code from another module into your program.

After importing, you can use functions, variables, or classes from that module.

Basic Import

python
import math

Now you can use the math module.

Example: square root

python
import math

print(math.sqrt(25))

Output

text
5.0

Import Your Own Module

If you created:

text
tools.py

With:

python
def hello():
    print("Hello")

Use it in another file:

python
import tools

tools.hello()

Output

text
Hello

Import Specific Item

Use from ... import ...

python
from math import sqrt

print(sqrt(16))

Output

text
4.0

Now you do not need math. before sqrt.

Import Multiple Items

python
from math import sqrt, pi

print(sqrt(9))
print(pi)

Output

text
3.0
3.141592653589793

Use an Alias

An alias is a shorter name.

python
import math as m

print(m.sqrt(36))

Output

text
6.0

Why Use Aliases?

Helpful when names are long.

Example:

python
import pandas as pd

Common Beginner Errors

Wrong File Name

The module name must match the file name.

File Not in Same Folder

Your file should be in the same project folder (for now).

Misspelled Function Name

Check spelling carefully.

Code Along

Import random.

Use:

python
random.randint(1, 10)

Mini Challenge

Create:

text
numbers.py

Add:

python
def triple(n):
    return n * 3

Import it and print:

text
15

Real World Use Case

Projects import modules for math, files, APIs, data tools, web apps, and reusable code.

Quiz

  1. What does import do?
  2. What is the difference between import math and from math import sqrt?
  3. What is an alias?
  4. Why do we import modules?

Assignment

Create your own module with one function and import it using an alias.

Summary

You learned how to import modules, import specific items, and use aliases in Python.