Files, Errors and Modules · Working at Scale · lesson 5 of 8
Modules and imports
about 12 minutes · free · runs in your browser
Borrowing code
A module is a file of Python. import gives you access to one:
import math
math.sqrt(16) # 4.0
from math import sqrt, pi
sqrt(16) # 4.0
import statistics as stats
stats.mean([1, 2, 3]) # 2
Three forms, three trade-offs. import math keeps the origin visible at every use site.
from math import sqrt is shorter but loses that. import ... as renames, which is
worth it for long names and nothing else.
What to avoid is from math import *: it dumps every name into your file, and when two
modules both define floor you will not be able to tell which one you got.
Your own files are modules too — import helpers finds helpers.py beside your script.
Your turn: import what you need and set root, circle_area and rounded_up
for a radius of 3.
You start from this, and edit it in the browser:
# Import from math, then compute the three values for radius 3.
radius = 3