Importing a Module
The functions you've used so far, such as print(), len() and sorted(), are in every Python program from the start. Python has many more, but most of them wait in modules until a program asks for them. A module is a file of Python code with functions and values for one subject. Python comes with a lot of modules, together called its standard library: math for mathematics, random for random numbers, statistics for averages, and many more.
To use a module, you import it: write the keyword import and the module's name. Then you reach what's in the module with its name, a dot and the name of the function:
import math
print(math.sqrt(16))
print(math.sqrt(2))
print(math.pi)4.0
1.4142135623730951
3.141592653589793math.sqrt() gives the square root of a number: the number that, multiplied by itself, gives the original one. 4 times 4 is 16, so the square root of 16 is 4. The result is always a decimal number, 4.0. math.pi isn't a function but a value stored in the module: the number π (pi), which you need for circles. That's why it has no parentheses.
The dot works as it does with methods: math.sqrt means “the function sqrt from the module math”. With the module's name in front, anyone who reads your code sees where each function comes from.
Imports go at the top of the program, each module once, however many times you use it. Then whoever reads the program sees at once which modules it needs.
Larger programs are split into several files, and each file is a module too: a program imports its own file shop.py with import shop, just as it imports math. In these exercises, a program is always one file, so you'll use the modules that come with Python.
Watch out for these mistakes:
- A missing import. The program doesn't know the name
math, and the error message even says what you forgot:NameError: name 'math' is not defined. Did you forget to import 'math'? - A typo in the module's name. The program ends right at the import:
import mathsgivesModuleNotFoundError: No module named 'maths'. - A typo in the function's name.
math.Sqrt(16)givesAttributeError: module 'math' has no attribute 'Sqrt'. Did you mean: 'sqrt'?The module has nothing calledSqrt(capital letters matter here too), and the message suggests the right name.
Instructions
- 1
The program ends with a
NameError. Read the error message and add the line that is missing at the top of the program. The program then printsSide: 12.0: each side of the playground is 12 meters long. - 2
Below, print the circumference of the sandpit, the length of its edge:
2 * math.pi * radius, with the labelCircumference:. The output should beCircumference: 12.566370614359172. Calculate it fromradius: the exercise also tries your program with another radius.