The math module
import math print(math.sqrt(144)) print(math.ceil(4.2), math.floor(4.8)) print(round(math.pi, 3)) print(math.gcd(24, 36))
Write Python. Understand every error.
Python basics · topic 15 of 25
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 floatmath.ceil(x) rounds up, math.floor(x) rounds downmath.pi the value of πmath.gcd(a, b) greatest common divisormath.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.
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.import maths. Read the ModuleNotFoundError guide.math. before a function after import math. Read the NameError guide.math.squareroot(9). Read the AttributeError guide.
import math print(math.sqrt(144)) print(math.ceil(4.2), math.floor(4.8)) print(round(math.pi, 3)) print(math.gcd(24, 36))
from math import sqrt, factorial print(sqrt(2)) print(factorial(5))
import random print(random.randint(1, 6)) print(random.choice(["mango", "litchi", "guava"])) # Run it again: the output changes each time
import datetime today = datetime.date.today() print(today) print(today.year)
5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
import math print(math.sqrt(49))
math.sqrt always returns a float.
import math print(math.ceil(4.2), math.floor(4.8))
ceil rounds up and floor rounds down.
from math import pi print(round(pi, 2))
round(x, 2) keeps two decimal places.
randint(1, 6) without writing random.?from module import name brings that name in directly.
import random random.seed(1) a = random.randint(1, 100) random.seed(1) b = random.randint(1, 100) print(a == b)
The same seed produces the same sequence of random numbers.