Python Arena
Step 1 of 3

Importing a module

Python has a few dozen functions built in, such as print, len and sum. Everything else lives in modules: files of ready-made functions and values, grouped by theme. Python comes with a large collection of them, called the standard library: a module for mathematics, one for random numbers, one for dates, one for reading CSV files, and hundreds more. This part of the course takes a tour of the most useful ones, and ends with modules you write yourself.

import

A module's contents aren't available until you ask for them. The import command loads a module and gives your program access to it. The math module has mathematical functions and constants:

import math

print(math.sqrt(49))
print(math.pi)
print(math.floor(7.8))
print(math.ceil(7.2))
Output
7.0
3.141592653589793
7
8

After import math, the program reaches everything in the module through the module's name and a dot: math.sqrt is the function sqrt of the module math.

  • sqrt gives the square root of a number, always as a float.
  • pi isn't a function but a value stored in the module, so it has no parentheses.
  • floor rounds down to a whole number, and ceil (short for ceiling) rounds up.

Imports go at the top of a program, one module per line, so a reader sees at a glance which modules the program uses.

When rounding up is right

Rounding up is what you need whenever the leftovers still need a place of their own. Ten people in cars that seat four need three cars, not 2.5:

import math

people = 10
seats = 4
print("Cars needed:", math.ceil(people / seats))
Output
Cars needed: 3

The module's name is part of the name

With import math, the names in the module are reached only through math. in front of them. Writing just sqrt doesn't work:

import math

print(sqrt(16))
Python stops with
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(sqrt(16))
          ^^^^
NameError: name 'sqrt' is not defined

And if the import line is missing, Python doesn't know the name math at all. Its message then suggests the fix itself: NameError: name 'math' is not defined. Did you forget to import 'math'?

Your task

Challenge 1 of 3

Fill in the blanks so the program imports the math module and prints the square root of 3 * 3 + 4 * 4 (the long side of a right triangle whose short sides are 3 and 4).

Challenge 2

An egg carton holds 12 eggs. Write a program that asks how many eggs there are and prints how many cartons are needed to pack them all. A carton that is only partly full still counts, so round up with math.ceil. For example:

Eggs: 30
Cartons: 3

Challenge 3

Write a function circle_area(radius) that returns the area of a circle: pi times the radius squared. Use math.pi, not a value of pi you type yourself.

circle_area(1) returns 3.141592653589793.