Importing Modules & the Standard Library
Modules
A module is just a .py file. Importing it gives you its functions, classes and variables.
Ways to import
| Code | Use as |
|---|---|
import math | math.sqrt(16) |
from math import sqrt | sqrt(16) |
import datetime as dt | dt.date.today() |
from math import * | ⚠️ avoid: you can't tell where names come from |
The standard library: "batteries included"
| Module | For |
|---|---|
math, random, statistics | numbers |
datetime | dates and times |
os, pathlib, shutil | files and folders |
json, csv | data formats |
collections, itertools | handy data tools |
re | regular expressions |
sys | interpreter info, arguments |
if __name__ == "__main__":
Code under this line runs only when the file is executed directly, not when it's imported. Put your script's entry point there.
▶️ Runs in the app.
Example
import math
import random
from datetime import date, timedelta
from collections import Counter
import statistics as stats
print(math.sqrt(16), math.pi) # 4.0 3.141592653589793
print(random.randint(1, 6)) # a dice roll, e.g. 4
today = date.today()
print(today + timedelta(days=7)) # the date one week from today
marks = [72, 88, 95, 60, 88]
print(stats.mean(marks), stats.median(marks)) # 80.6 88
print(Counter(marks).most_common(1)) # [(88, 2)]
def main():
print("Running as a script")
if __name__ == "__main__":
main()