
Code
Borrowing Tools
A module is a file of Python code you can reuse. Python ships
with hundreds of them, called the standard library. You load
one with import.
import math # the whole module
print(math.sqrt(16)) # 4.0 (module.name)
from math import ceil # copy one name into your file
print(ceil(2.1)) # 3 (no prefix needed)
import statistics as stats # a shorter nickname (alias)
print(stats.mean([2, 4])) # 3
Which style should you use?
import mathkeeps it obvious wheremath.sqrtcomes from.from math import ceilis handy for a few names you use a lot.asgives a long module name a short alias.- Avoid
from math import *: it dumps every name into your file, and you can't tell where anything came from.
Assignment
import mathand completedistance(x1, y1, x2, y2)so it returns the straight-line distance between two islands, usingmath.sqrt(ormath.hypot).from math import ceiland completeboats_needed(people, seats), the number of boats to carry everyone (round up).import statistics as statsand completeaverage_depth(depths)withstats.mean, rounded to 1 decimal place.
import mathand completedistance(x1, y1, x2, y2)so it returns the straight-line distance between two islands, usingmath.sqrt(ormath.hypot).from math import ceiland completeboats_needed(people, seats), the number of boats to carry everyone (round up).import statistics as statsand completeaverage_depth(depths)withstats.mean, rounded to 1 decimal place.
main.py Python sleeping
Press Run to try your code, then Check to test it.