🌱BeginnerWorking with Python
Modules and Imports
Using Python's standard library and third-party packages with import, from...import, and pip.
Overview
A module is simply a Python file (.py) that contains functions, classes, and variables you can reuse in other files. Python ships with an extensive standard library of modules covering math, file I/O, networking, date/time, JSON, regular expressions, and hundreds of other domains all available without installing anything extra.
You bring a module into your code with the import statement. There are several forms:
- `import math` imports the entire module; access items with `math.sqrt(4)`
- `from math import sqrt` imports just sqrt; call it as `sqrt(4)`
- `from math import sqrt, pi, floor` import multiple names at once
- `import math as m` imports with an alias; `m.sqrt(4)` saves typing
For third-party packages (not in the standard library), you install them with pip: `pip install requests`. The virtual environment system (venv) isolates project dependencies so different projects can use different package versions.
Key Points
- •`import module` imports a module; access its contents as `module.name`
- •`from module import name` imports a specific name into the current namespace
- •`import module as alias` lets you use a shorter name (e.g. `import numpy as np`)
- •Standard library highlights: math, random, os, sys, datetime, json, pathlib, collections
- •Third-party packages installed via pip: `pip install package-name`
- •Virtual environments (venv) isolate package versions per project always use them
- •Write your own modules: any .py file is a module; import it by its filename (without .py)
Examples
Using the math and random modules
import math
import random
print(math.sqrt(144)) # 12.0
print(math.pi) # 3.141592653589793
print(math.floor(3.9)) # 3
print(math.ceil(3.1)) # 4
print(math.log(100, 10)) # 2.0
# random module
print(random.random()) # float between 0.0 and 1.0
print(random.randint(1, 10)) # int between 1 and 10 inclusive
names = ["Alice", "Bob", "Carol"]
print(random.choice(names)) # random pick from list
random.shuffle(names)
print(names) # shuffled in placedatetime and json modules
from datetime import datetime, timedelta
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M")) # e.g. "2026-01-15 14:30"
tomorrow = now + timedelta(days=1)
print(tomorrow.date())
import json
data = {"name": "Alice", "scores": [95, 82, 91]}
json_str = json.dumps(data) # Python dict → JSON string
print(json_str)
parsed = json.loads(json_str) # JSON string → Python dict
print(parsed["name"]) # Aliceos and pathlib for file system operations
import os
from pathlib import Path
# Current working directory
print(os.getcwd())
# pathlib modern, object-oriented file paths
p = Path(".")
print(list(p.iterdir())) # list files and folders
home = Path.home()
print(home) # e.g. /Users/alice or C:\Users\alice
# Join paths safely (works on all OS)
config_path = home / ".config" / "myapp" / "settings.json"
print(config_path)pathlib (Python 3.4+) is preferred over os.path for file path handling.
Common Mistakes
- Naming your file the same as a standard library module (e.g. math.py) your file will shadow the stdlib module
- `from module import *` pollutes your namespace with all names only use in exploratory code, never in production
- Forgetting to activate a virtual environment before installing packages packages may install globally instead
Note
The Python standard library documentation (docs.python.org/3/library/) is one of the best-written references in programming. Before reaching for a third-party package, check if the stdlib already has what you need.
Exercises
Write Python code to solve each exercise. Run it in your browser and check your output.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4