Block 6: Modules & the math Library
Import and use standard library modules, starting with math.
Concepts
- import module and import module as alias
- math.sqrt, math.pi, math.ceil, math.floor
- math.log, math.pow
- Using help() and dir() to explore modules
Code Examples
math module basics
import math
print(math.pi)
print(math.sqrt(16))
print(math.pow(2, 10))
Exploring with help() and dir()
import math
print(dir(math)[:5]) # First 5 attributes
# help(math.sqrt) # Uncomment to see docs
Exercise
Write circle_area(r) and sphere_volume(r) using math.pi. Compute the hypotenuse of a right triangle with sides 3 and 4.
Solution
import math
def circle_area(r):
return math.pi * r ** 2
def sphere_volume(r):
return (4/3) * math.pi * r ** 3
a, b = 3, 4
hyp = math.sqrt(a**2 + b**2)
print(f'Circle area (r=5): {circle_area(5):.2f}')
print(f'Sphere volume (r=2): {sphere_volume(2):.2f}')
print(f'Hypotenuse: {hyp}')Practice Problems
Problem 1: Use math.ceil and math.floor to round 3.7 up and down.
Hint: math.ceil(3.7), math.floor(3.7)
Problem 2: Compute log base 10 of 1000 using math.log
Hint: math.log(1000, 10)
Application
Scientific computing relies heavily on math—logarithms for scaling, sqrt for distances, pi for geometry.
Case Study
A physics simulation uses math.sin, math.cos for projectile motion. math.sqrt appears in distance calculations for collision detection.
Homework
Explore the random module: generate 5 random integers between 1 and 10.