Python · Module 7 · Lesson 11 min read

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

CodeUse as
import mathmath.sqrt(16)
from math import sqrtsqrt(16)
import datetime as dtdt.date.today()
from math import *⚠️ avoid: you can't tell where names come from

The standard library: "batteries included"

ModuleFor
math, random, statisticsnumbers
datetimedates and times
os, pathlib, shutilfiles and folders
json, csvdata formats
collections, itertoolshandy data tools
reregular expressions
sysinterpreter 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

Python
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()