Built-ins and The Standard Library

math

What does this do?

>>> import math

This imports a module called math.

We didn’t make a module called math though… where is this coming from?

Python comes bundled with a bunch of modules that we call the “standard library”.

The math module has a number of useful things in it:

>>> math.pi
3.141592653589793
>>> math.e
2.718281828459045
>>> math.sqrt(121)
11.0

With the math.pi constant, we can calculate the area of a circle to the greatest precision possible on the machine:

>>> import math
>>> radius = 2.75
>>> area = math.pi * radius ** 2
>>> area
23.75829444277281

There is also math.ceil(x), which rounds numbers up:

>>> math.floor(area)
23
>>> math.floor(math.pi)
3

And math.floor(x) which rounds numbers down:

>>> math.floor(area)
23
>>> math.floor(math.pi)
3

Review

What else have we imported that we didn’t make ourselves?

We imported from sys to read command-line arguments:

>>> import sys
>>> sys.argv
['']

Built-ins

Some things don’t even require an import to use.

What functions have we used in Python (that we didn’t make ourselves)?

>>> print("Hi!")
Hi!
>>> str(4)
'4'
>>> int('4')
4

Python comes with many other built-ins that we haven’t seen yet.

There’s round:

>>> round(145.775, 2)
145.78

And abs:

>>> abs(4)
4
>>> abs(-4)
4

And input, which allows us to write programs that prompt users for input:

>>> def greet_user():
...     name = input("Please enter your name: ")
...     print(f"Hello {name}!")
...
>>> greet_user()
Please enter your name: Trey
Hello Trey!

And a few dozen more, though you’ll likely only reach for about 20 of them frequently. We’ll see a handful more of these later.