All courses › Programming with Python › Modules and import

Modules and import

A module is a file of ready-made functions you can use in your own program. The standard library has many, such as math, random and csv. You can also make your own modules by putting functions in a separate file and importing it.

import math\texttt{import math}import the whole module, use math.sqrt
from math import sqrt, pi\texttt{from math import sqrt, pi}import specific names
import numpy as np\texttt{import numpy as np}import with a shorter name

Symbols

math\texttt{math}mathematical functions
random\texttt{random}random numbers
csv\texttt{csv}read and write table files

Example

The hypotenuse of a triangle with legs 3 and 4:

math.hypot(3, 4)\texttt{math.hypot(3, 4)} gives 5.0.

Avoid from module import *. Then you no longer know where names come from.
Practise files, errors and modules for free →

← Error handling

Part of Programming with Python: Files, errors and modules.