You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
As your programs grow, splitting code into separate files keeps things organised. Python's module system lets you do exactly that, and the wider Python ecosystem of packages gives you access to thousands of pre-built libraries.
A module is simply a Python file. Any .py file is a module you can import into another file.
# math_utils.py
def add(a, b):
return a + b
def square(x):
return x * x
PI = 3.14159
# main.py
import math_utils
print(math_utils.add(3, 4)) # 7
print(math_utils.square(5)) # 25
print(math_utils.PI) # 3.14159
# Import whole module
import math
print(math.sqrt(16)) # 4.0
# Import specific names
from math import sqrt, pi
print(sqrt(25)) # 5.0
print(pi) # 3.141592653589793
# Import with an alias
import math as m
print(m.floor(3.7)) # 3
# Import everything (not recommended — pollutes namespace)
from math import *
Python ships with a rich standard library — no installation needed:
import os # operating system interfaces
import sys # system-specific parameters
import math # mathematical functions
import random # random number generation
import datetime # date and time handling
import json # JSON encoding and decoding
import re # regular expressions
import collections # specialised container types
import math
import random
print(math.ceil(4.2)) # 5
print(math.floor(4.9)) # 4
print(math.pow(2, 8)) # 256.0
print(random.randint(1, 6)) # random die roll
print(random.choice(["a", "b", "c"])) # random element
A package is a directory containing multiple modules and an init.py file. Packages let you organise related modules into a hierarchy:
myapp/
__init__.py
utils/
__init__.py
string_helpers.py
math_helpers.py
models/
__init__.py
user.py
from myapp.utils.string_helpers import capitalise
from myapp.models.user import User
Python's package manager pip installs packages from the Python Package Index (PyPI):
pip install requests
pip install numpy
pip install pandas
Then import and use them:
import requests
response = requests.get("https://api.example.com/data")
print(response.status_code) # 200
print(response.json()) # parsed JSON
def greet(name):
return f"Hello, {name}!"
if __name__ == "__main__":
# This runs only when the file is executed directly,
# not when it is imported as a module
print(greet("World"))
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.