Modules and the standard library

INPUT · Slides

Leave the sums to somebody else

01 / 07

Working out the area of a circle

The area of a circle is radius × radius × pi. Pi is where it gets awkward.

You could write 3.14 yourself, but every digit you leave off pushes the answer further out. Working pi out for yourself, on the other hand, is a serious undertaking.

Sums like this — the ones everybody needs — live in a module called math that comes with Python. One line, import math, and it is yours. Nothing to install, nothing to configure.

02 / 07

Square roots come from math.sqrt

The square root — the number that gives you your number when multiplied by itself — comes from math.sqrt. The name is short for square root.

The answer always comes back as a decimal. Notice that math.sqrt(16) is 4.0, not 4.

import mathprint(math.sqrt(16))print(math.sqrt(2))

Result

4.0
1.4142135623730951

03 / 07

Pi is math.pi

math.pi is pi. The point to take here is that it is a value, not a function. No brackets on it.

math.sqrt() wants a number in its brackets; math.pi is already a number in itself. Use it exactly as you would a variable.

import mathprint(math.pi)radius = 3print(math.pi * radius ** 2)

Result

3.141592653589793
28.274333882308138

04 / 07

Rounding down and rounding up

math.floor — a floor is below you — takes a number down. math.ceil, from ceiling, takes it up. Both hand back a whole number.

math.ceil earns its keep whenever a remainder still counts as one more: how many boxes do I need if three fit in a box.

import mathprint(math.floor(3.7))print(math.ceil(3.2))

Result

3
4

05 / 07

Some of them need no import

round, which goes to the nearest, and abs, which gives the size with the sign taken off, are built-in functions, so they need no import. The names are there from the start.

round goes to whichever is nearer; math.floor always goes down. For 3.7, round gives 4 and math.floor gives 3. Decide which one you actually want, then pick.

print(round(3.456, 2))print(abs(-5))

Result

3.46
5

06 / 07

math.pow against **

math.pow(a, b) is a to the power of b — the same sum as the ** you met in Chapter 1.

What differs is the type that comes back. math.pow always returns a decimal, so if you want to stay with whole numbers, is the plainer choice. When two tools give the same answer, pick on what you are going to do with it next**.

import mathprint(math.pow(2, 3))print(2 ** 3)

Result

8.0
8

07 / 07

Do not memorise — go looking

math holds plenty more: math.log for logarithms, math.sin for trigonometry, and so on. There is no need to learn them all.

Here is what to take away. Stop and ask whether somebody has already made this. Look inside math before you start writing your own square root — that habit is the most valuable thing in this chapter.