Lesson 11: Modules & Imports

1. What are Modules?

Modules are Python files containing functions, classes, variables — reusable code.

Python comes with many built-in modules (math, random, datetime).

ML uses external modules: numpy, pandas, sklearn, tensorflow.

Exercise 1

Which line imports the math module correctly?

2. Common Imports & Usage

# Basic import
import math
print(math.sqrt(16))  # 4.0

# Import specific functions
from math import sqrt, pi
print(sqrt(25))       # 5.0
print(pi)             # 3.14159...

# Alias for shorter name
import numpy as np
arr = np.array([1, 2, 3])

Best practice: use specific imports or aliases to avoid name conflicts.

Exercise 2

Import and use random:

import  as rnd
number = rnd.randint(1, 10)
print(number)  # random int 1–10

Exercise 3

Which are valid ways to import?
← Previous Lesson (10) Next Lesson (12) →