SythraOpen app

Libraries and Modules in Python

A module in Python is a file of pre-built functions you bring into your program with import, so you don't have to write everything yourself. The math and random modules are two of the most commonly used.

Sythra

7 min read

XLinkedIn
Libraries and Modules in Python — cover illustration

Imagine you are building a treehouse. You could make your own hammer from scratch — chop down a tree, carve the wood, forge the metal. But that would take forever, and someone has already made a great hammer, so you just pick one up and use it.

Libraries and modules in Python work the same way. Thousands of tools have already been built and tested by other programmers. Instead of writing everything yourself, you can simply borrow them with import. This page covers what a module actually is, how to import one, and the two modules you'll reach for constantly: math and random.

What you will learn

  • What a module actually is under the hood
  • How import and from ... import work
  • The most useful tools in the math module
  • How to add randomness with the random module
  • A worked example combining both

What even is a module?

A module is just a Python file full of functions someone else already wrote. Instead of you figuring out how to calculate a square root from scratch, someone already did that work and put it inside a module called math. You just ask Python to bring it over.

Think of it like a toolbox. Python comes with several toolboxes already sitting in the garage — you do not need to carry them around with you, you just call for the one you need when you need it. A collection of modules bundled together is often called a library.

How to import a module

The word for "bring me that toolbox" in Python is import. You write it at the very top of your file, before anything else:

import math

That one line gives you access to everything inside the math module. To use something from it, you write the module name, a dot, and then the tool name:

import math

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

The dot is just Python's way of saying "go inside this toolbox and grab that specific tool."

Importing just what you need

Sometimes you only need one or two things from a module and you do not want to keep writing the module name every time. You can import specific things directly using from:

from math import sqrt, pi

print(sqrt(25))    # 5.0
print(pi)          # 3.141592653589793

Now you can use sqrt and pi directly without the math. in front. Both styles work — it is just a matter of preference and clarity. For beginners, the import math style is usually better because it makes it obvious where each tool is coming from.

MethodExample usageDot notation?Risk
import mathmath.piRequiredNone
from math import pipiNot neededLow
from math import *pi, cos, sqrtNot neededName conflicts

The wildcard import (from math import *) feels convenient but becomes dangerous in larger programs — it can silently overwrite your own variables if any of your names match something inside the module. Stick to explicit imports unless you have a good reason.

The math module: numbers and calculations

The math module is full of tools for doing math that goes beyond basic +, -, *, /:

import math

math.sqrt(16)        # 4.0    square root
math.pi              # 3.14159...  the value of pi
math.floor(3.9)      # 3      round DOWN to nearest whole number
math.ceil(3.1)       # 4      round UP to nearest whole number
math.pow(2, 3)       # 8.0    2 to the power of 3 (same as 2**3)
math.log(100, 10)    # 2.0    logarithm base 10 of 100

math.sqrt() always gives back a float, even if the answer is a whole number — math.sqrt(25) gives 5.0, not 5. math.floor() and math.ceil() are useful when you need a whole number but are working with decimals — for example, figuring out how many full boxes fit in a truck.

The random module: doing things by chance

The random module lets you introduce randomness into your programs — like rolling a dice or shuffling a deck of cards:

import random

random.random()              # a random float between 0.0 and 1.0
random.randint(1, 6)         # a random whole number between 1 and 6 (like a dice roll)
random.choice(['red', 'blue', 'green'])   # picks one item at random from a list
random.shuffle([1, 2, 3, 4, 5])           # shuffles a list in place

random.random() gives you a float somewhere between 0.0 and 1.0 — useful when you want a percentage or probability. random.randint(a, b) is more practical for games — both a and b are included in the possible results.

Putting it all together

Here is a small program that uses everything from this page at once, so you can see how these tools connect in real code:

import math
import random

scores = [88, 45, 92, 67, 34, 78, 91]

scores.sort()
print('Scores in order:', scores)

print('Highest:', max(scores))
print('Lowest:', min(scores))

average = sum(scores) / len(scores)
print('Average:', round(average, 2))

print('Square root of highest:', round(math.sqrt(max(scores)), 2))
print('Random score picked:', random.choice(scores))

Every tool used here — math, random, sort, max, min, sum, len, round — is either a module import or a built-in function.

Common mistakes

  • Forgetting the import line and getting a NameError when using a module's function
  • Using from module import * in a large file and accidentally shadowing your own variable names
  • Calling a module function without the dot notation after a plain import math
  • Assuming math.sqrt() returns an integer when it always returns a float

Common questions

What is a module in Python?

A module is a Python file containing pre-written functions and values. Instead of writing that code yourself, you bring it into your program with the import keyword.

What is the difference between import math and from math import sqrt?

import math gives you access to everything in the module via dot notation, like math.sqrt(). from math import sqrt imports only sqrt directly, so you call sqrt() without the math. prefix.

Why should I avoid from module import *?

The wildcard import brings every name from the module into your file at once, which can silently overwrite your own variables or functions if any names collide. Explicit imports make it clear where each name comes from.

Does math.sqrt() return an int or a float?

math.sqrt() always returns a float, even when the result is a whole number — math.sqrt(25) returns 5.0, not 5.

What is the difference between a library and a module in Python?

A module is a single Python file of functions. A library is often a collection of related modules bundled together, though the terms are frequently used interchangeably in casual conversation.

Explore

Related topics

Keep going — these sit next to this concept in a real learning path.

Browse all python explainers →