PyForge ยท Python practice library
All topics

Topic 13 of 17

Modules & Packages

Reuse code with imports, standard library highlights, and pip.

import / from
Aliases
Standard library
pip & venv

Basic

2 programs

Program 1

Use the math module

Basic

Import and call math functions.

python
import math

print(math.sqrt(16))
print(math.pi)
print(math.factorial(5))

Program 2

Random numbers

Basic

Generate random data.

python
import random

print(random.randint(1, 10))
print(random.choice(["red", "green", "blue"]))
print(random.sample(range(100), 5))

Intermediate

1 program

Program 1

Working with dates

Intermediate

Use datetime for date arithmetic.

python
from datetime import datetime, timedelta

now = datetime.now()
print("Now:", now.strftime("%Y-%m-%d %H:%M"))
print("Next week:", now + timedelta(days=7))

Advanced

1 program

Program 1

Create your own module

Advanced

Split code across files and import.

python
# file: mymath.py
def add(a, b):
    return a + b

def mul(a, b):
    return a * b

# file: main.py
import mymath
print(mymath.add(2, 3))
print(mymath.mul(4, 5))