Write Python. Understand every error.

Starting Python in your browser…

Python basics · topic 15 of 25

Modules: math and friends

A module is a file of ready-made code that you can use in your programs. Python comes with many, and you load one with import.

import math
print(math.sqrt(49))   # 7.0
print(math.pi)

After import math, you write math. before each function. With from math import sqrt you can write sqrt(49) directly.

  • math.sqrt(x) square root, always a float
  • math.ceil(x) rounds up, math.floor(x) rounds down
  • math.pi the value of π
  • math.gcd(a, b) greatest common divisor
  • math.factorial(n) n!

Other useful modules include random for random numbers and datetime for dates. Packages that do not come with Python, such as NumPy, are installed separately in a normal setup. This app includes a teaching version of NumPy, covered in its own topics.

Key takeaways

  • import math gives access to the math module, used as math.sqrt(16).
  • from math import pi lets you write pi directly.
  • math.sqrt always returns a float, math.ceil rounds up and math.floor rounds down.
  • random.seed(n) makes random numbers repeatable, which helps when you test a program.

Common mistakes

Practise with these programs

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.