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 math keeps it obvious where math.sqrt comes from.
  • from math import ceil is handy for a few names you use a lot.
  • as gives 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

  1. import math and complete distance(x1, y1, x2, y2) so it returns the straight-line distance between two islands, using math.sqrt (or math.hypot).
  2. from math import ceil and complete boats_needed(people, seats), the number of boats to carry everyone (round up).
  3. import statistics as stats and complete average_depth(depths) with stats.mean, rounded to 1 decimal place.