Module 12 of 15 · Python for AI — Complete Beginner Course · Beginner

Modules, Packages, and Libraries

Duration: 5 min

As your code grows, you'll want to organize it into modules and packages. You'll also use external libraries to avoid reinventing the wheel.

Learn more: https://docs.python.org/3/tutorial/

Importing Modules

# Import entire module
import math
print(math.sqrt(16))  # 4.0
print(math.pi)        # 3.14159...

# Import specific function
from math import sqrt, pi
print(sqrt(16))  # 4.0
print(pi)        # 3.14159...

# Import with alias
import numpy as np
array = np.array([1, 2, 3])

# Import all (not recommended)
from math import *
print(cos(0))  # 1.0

Try it in Google Colab: Open in Colab

Creating Your Own Module

# Save this as my_module.py

def greet(name):
    return f"Hello, {name}!"

def add(a, b):
    return a + b

PI = 3.14159

if __name__ == "__main__":
    print("This runs only when executed directly")
    print(greet("Alice"))
# Use the module
from my_module import greet, add, PI

print(greet("Bob"))  # 'Hello, Bob!'
print(add(5, 3))     # 8
print(PI)            # 3.14159

Installing External Libraries

# Install a library
pip install numpy

# Install specific version
pip install numpy==1.21.0

# Install multiple libraries
pip install numpy pandas matplotlib

# Upgrade a library
pip install --upgrade numpy

# List installed packages
pip list

# Save requirements to file
pip freeze > requirements.txt

# Install from requirements file
pip install -r requirements.txt

💡 Tip: Use name == 'main' to write code that runs only when the file is executed directly.

❓ What does 'from math import sqrt' do?

❓ What is a best practice when working with Modules, Packages, and Libraries?

💡 Tip: Pro Tip: Master Modules, Packages, and Libraries thoroughly before moving to advanced topics. This foundation is crucial for writing professional Python code.

← Previous Continue interactively → Next →

Related Courses