livepython.net
CHAPTER 18Python Modules
18.1  IMPORT

Python Import: How to Use Modules

What Is a Module in Python?

A module is a file of Python code that someone already wrote for you, full of ready-made functions. You bring it into your program with the import keyword, then use its functions with a dot: math.sqrt().

PYTHONedit me
import math

print(math.sqrt(25))
print(math.pi)
OUTPUT
5.0
3.141592653589793

import math loads the math module. After that, math.sqrt(25) means "the sqrt function that lives inside math". It gives back the square root, 5.0.

Think of it like a toolbox in the garage. Python doesn't carry every tool around all the time. When you need a drill, you open the right toolbox first (import), then take out the drill (math.sqrt).

The rules

  • Write import and the module's name, usually at the very top of the file.
  • Use a function from it as module.function(), with a dot in between.
  • Import a module once per program. Every line below can use it.
  • Python comes with hundreds of modules, called the standard library. They are already installed: no download needed.

A few modules from the standard library

ModuleWhat it gives youExample
mathmaths functions and numbersmath.sqrt(16)
randomrandom numbers and picksrandom.randint(1, 6)
datetimedates and timesdatetime.date(2025, 3, 14)

You'll meet all three in this chapter.

Avoid: using a module before you import it

PYTHONedit me
print(math.sqrt(25))
OUTPUT
NameError: name 'math' is not defined

Don't be scared of this error! It's the same NameError you saw for a variable that doesn't exist. Python doesn't know the name math until you import it.

Common beginner doubt: "Are print() and len() from a module too?" They are built-in functions: Python always has them ready, with no import. Modules hold the extra tools you only need sometimes.

import a module once at the top, then use its tools with a dot: math.sqrt(25).

your turnPick the right idea

What does import math do?

Think about it, then pick one.
your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.

from math import sqrt: Import One Function

With from ... import ... you take only the functions you need out of a module. Then you call them by their own name, with no module name and no dot.

PYTHONedit me
from math import sqrt, gcd

print(sqrt(81))
print(gcd(12, 18))
OUTPUT
9.0
6

gcd() finds the greatest common divisor: the biggest whole number that divides both numbers. 6 divides 12 and 18, and nothing bigger does.

Think of it like borrowing from a neighbour. import math borrows the whole toolbox, and you say "toolbox, drill" every time. from math import sqrt borrows only the drill, so you can just say "drill".

Two ways, side by side

You writeThen you callGood for
import mathmath.sqrt(81)many functions; it's always clear where they come from
from math import sqrtsqrt(81)one or two functions you use a lot
  • List several names with commas: from math import sqrt, pi, gcd.
  • Only the names you list are imported. The name math itself is not.

Avoid: using the module name after from ... import

PYTHONedit me
from math import sqrt

print(math.sqrt(81))
OUTPUT
NameError: name 'math' is not defined

You imported sqrt, not math. Write sqrt(81), or change the first line to import math.

Avoid: from math import *

The star * imports every name in the module at once. It works, but it fills your program with hundreds of names you can't see. If one of them has the same name as your variable, one quietly replaces the other. The PEP 8 style from chapter 16 says to avoid it. Name what you need instead.

Common beginner doubt: "Which way is better?" Both are fine. import math is clearer in a long program: a reader sees math. and knows where sqrt lives.

from math import sqrt gives you sqrt() by itself; the name math is not imported.

your turnPredict the output

What will this print?

from math import sqrt print(sqrt(49))
Your turn! What will this code show on the screen?
your turnFill the gap

Import gcd straight from the math module

from math ? gcd print(gcd(12, 18))

It should print: 6

Which piece makes this code work?

import as: Give a Module a Short Name

The keyword as gives a module (or a function) a new, shorter name while you import it. This new name is called an alias (a nickname).

PYTHONedit me
import math as m

print(m.sqrt(36))
print(m.floor(4.8))
OUTPUT
6.0
4

After import math as m, you write m. instead of math.. Same module, same functions, a shorter name. (floor() rounds down; you'll meet it properly in the next topic.)

Think of it like a friend called Alexander who everyone calls Alex. Same person, shorter name.

The rules

  • import module as nickname: use nickname.function() from then on.
  • from module import function as nickname: use nickname() from then on.
  • The original name is not created. After import math as m, the name math doesn't exist.
  • Pick a nickname that is short but still clear.

Rename one function

PYTHONedit me
from math import sqrt as root

side = root(64)
print("Side:", side)
OUTPUT
Side: 8.0

Nicknames people really use

Some aliases are so common that every Python programmer knows them. You'll see import datetime as dt in this chapter. When you read code from others, you'll also meet ones like import numpy as np: numpy is not part of the standard library, so it must be installed first.

Avoid: the old name after an alias

PYTHONedit me
import math as m

print(math.pi)
OUTPUT
NameError: name 'math' is not defined

You told Python to call the module m, so the name math was never made. Use m.pi.

Common beginner doubt: "Should I give every module an alias?" No. math and random are already short and clear. Use an alias when a name is long, or when everyone else uses that alias too.

import math as m gives the module a nickname; from then on, write m. instead of math.

your turnType the output

Type what this prints

import math as m print(m.floor(3.7))
Read the code line by line, then type the output exactly.
your turnPick the right idea

After from math import sqrt as root, which call works?

Think about it, then pick one.

Your Own Modules, and Why Not to Name a File math.py

Any .py file is a module. Put your functions in one file, and another file in the same folder can import them by the file's name, without the .py.

Think of it like a recipe card you wrote yourself. Once it's in your kitchen drawer, you can use it in any meal, just like the recipes from a cookbook.

The file greetings.py:

def hello(name):
    return "Hello, " + name + "!"

The file main.py, in the same folder:

import greetings

print(greetings.hello("Sunny"))   # Output: Hello, Sunny!

The browser editor on this site runs one file at a time, so try this one on your own computer.

Where Python looks for a module

When you write import math, Python searches in this order:

  1. The folder of the program you are running.
  2. The standard library that came with Python.
  3. Extra packages that were installed separately (with a tool called pip; this course doesn't need any).

Avoid: naming your file after a module

Because your own folder is searched first, a file called math.py or random.py hides the real module. Then import random loads your file instead, and you get a strange error like this:

AttributeError: module 'random' has no attribute 'randint'

Python found your random.py, and it has no randint(). The fix: rename your file, for example to dice_game.py.

Avoid: a typo in the module name

PYTHONedit me
import maths
OUTPUT
ModuleNotFoundError: No module named 'maths'

Every error is a clue! ModuleNotFoundError means Python searched everywhere and found no module with that name. Check the spelling: it's math, with no s.

Common beginner doubt: "So which names are safe for my files?" Any name that isn't a module you use. Names that say what the program does, like shopping_list.py, are always safe.

Your own .py files are modules too. Never name one math.py or random.py, or it hides the real module.

your turnPick the right idea

Rocky saves his dice game as random.py. Inside it, random.randint() fails. Why?

Think about it, then pick one.
your turnPredict the output

Remember return from chapter 15?

def double(n): return n * 2 print(double(4) + 1)
Your turn! What will this code show on the screen?

Practice: Import

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 160.Python Program to Find the Square Root Using the math ModuleEasySolve
  2. 161.Python Program to Find the GCD and LCM of Two NumbersMediumSolve