Phone makers buy their parts
A phone maker does not make the screen, the camera and the battery from nothing. They buy parts that other people made and tested.
Programmers do the same. Other people wrote and tested code for common jobs. You can use it. This lesson shows where it comes from, and its good and bad points.
Key words
| Word | What it means | Example |
|---|---|---|
| Pre-written code | Code that somebody else wrote, tested and shared. | |
| User-written code | Code that you write yourself for your own program. | |
| Built-in function | A function that is part of Python. It is always there. | len(), max(), round() |
| Library | A collection of pre-written code for one kind of job. | math, random |
| import | The Python word that makes a library ready to use. | import math |
| Third-party library | A library made by another company or group. You install it first. | pandas |
| Function | A named piece of code that gives back a result. | |
| Licence | The rules for how you may use somebody else's code. | free to use, but you must name the author |
The cells students fill in are left blank in this preview.
Four places code comes from
| Where from | Who wrote it | Example | Do you import it? |
|---|---|---|---|
| User-written | You | def ticket_cost() | No |
| Built into Python | The Python team | len(), print(), round() | No |
| Python library | The Python team | `math.sqrt()`, `random.randint()` | Yes: import math |
| Third-party library | Another group | pandas, matplotlib | Install it, then import it |
The cells students fill in are left blank in this preview.
Try it: built-in functions
prices = [3.5, 1.2, 2.0]
print(len(prices))
print(max(prices))
print(min(prices))
print(round(7.6))
print(prices.count(2.0))
print(ord("A"))
print(chr(66))
# Add another price to the list and run it again.
Make a free account to save your work and track your progress.
Try it: the math library
import math
print(math.floor(7.6))
print(math.ceil(7.6))
print(math.trunc(-7.6))
print(math.sqrt(81))
print(math.pow(2, 5))
print(math.pi)
# Try math.floor(-7.6). What do you expect?
Make a free account to save your work and track your progress.
What the math functions give
| You write | It gives | In words |
|---|---|---|
| math.floor(7.6) | 7 | Down to the whole number below |
| math.ceil(7.6) | 8 | Up to the whole number above |
| math.trunc(-7.6) | -7 | Cut off the decimal part |
| round(7.6) | 8 | To the nearest whole number |
| `math.sqrt(81)` | 9.0 | The square root: 9 times 9 is 81 |
| math.pow(2, 5) | 32.0 | Five 2s multiplied: 2 x 2 x 2 x 2 x 2 |
The cells students fill in are left blank in this preview.
Try it: the random library
import random
print(random.randint(1, 6))
print(random.random())
print(random.uniform(1, 10))
print(random.sample(["Sam", "Aisha", "Tom", "Mei"], 2))
# Run it three times. The answers change.
Make a free account to save your work and track your progress.
Quick check: where does it come from?
Have a go
Quick check: where does it come from?
3 questionsFix it: the missing import
print(math.ceil(2.1))
# Run it. Read the error. Python does not know the name math.
# Add one line at the top to fix it.
Make a free account to save your work and track your progress.
Third-party libraries
Some jobs are big. Reading a data file and drawing a chart are two of them. People wrote third-party libraries for them. pandas works with tables of data. matplotlib draws charts.
You install them first. Then you import them.
Benefits (good points) of pre-written code
| Benefit | Why it helps |
|---|---|
| Saves time | The job is already done |
| Well tested | Many people have used it, so there are fewer bugs |
| Often faster | It is often quicker than code you would write |
| Help is easy to find | Many programmers use the same code and share answers |
| Shorter code | The program is easier to read |
The cells students fill in are left blank in this preview.
Drawbacks (bad points) of pre-written code
| Drawback | Why it matters |
|---|---|
| You may not know how it works inside | It is hard to be sure it does exactly what you need |
| A bug inside it is hard to fix | You did not write it, so you wait for somebody else to fix it |
| A third-party library may stop being updated | Old code can stop working or have security holes |
| It can be bigger than you need | It uses more space and memory |
| It may have a licence | You must follow its rules, and some do not allow every use |
The cells students fill in are left blank in this preview.
Match the job to the code
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Your turn: use the libraries
Use pre-written code to finish four functions. pages_needed(items, per_page) gives back how many pages are needed: use math.ceil. circle_area(radius) uses math.pi. cheapest(prices) uses min. lucky_dip(numbers, k) picks k different numbers from the list: use random.sample. The imports are already at the top. Press Run Tests to check.
import math
import random
def pages_needed(items, per_page):
# Each page holds per_page items. Give back how many pages are needed.
# 10 items with 4 on a page need 3 pages. Use math.ceil().
return None
def circle_area(radius):
# Give back the area of a circle: pi times the radius times the radius.
# Use math.pi.
return None
def cheapest(prices):
# Give back the lowest price in the list. Use min().
return None
def lucky_dip(numbers, k):
# Give back k different numbers picked at random from the list.
# Use random.sample().
return None
Make a free account to save your work, or press Start lab to work through the whole lesson.
Extra: Installing a library and reading its instructions
You install a third-party library with a tool called pip. pip is a program that downloads libraries for Python. On your own computer you type pip install pandas.
Every good library has documentation. Documentation is the set of instructions that says what each function does. Read it before you use a new function. Check the licence there too.
Watch: code you did not write
Press Play on the short film below. It uses a built-in function, then a library function, first without its import and then with it. It reads the documentation to find what a function takes and gives back. Watch what happens when you guess which function to use.
Film: using code that others wrote
Using code that others wrote
Every scene, as text
- Some code is built into Python and is always there. prices = [3.5, 1.2, 2.0] makes a list, and print(min(prices)) prints 1.2, the lowest price. You did not write min and you did not import it: min is a built-in function.
- math.ceil comes from the math library, a collection of pre-written code for one kind of job. Run print(math.ceil(2.1)) alone and Python stops: NameError: name 'math' is not defined. Did you forget to import 'math'?
- The cure is one line at the top: import math. import makes the library ready to use. Now print(math.ceil(2.1)) prints 3: 2.1 rounded up to the whole number above.
- Before you use a function you did not write, read its documentation, the instructions that say what it does. math.ceil(x) takes x, a number, and gives back the smallest integer greater than or equal to x. So print(math.ceil(7.6)) prints 8.
- Myth (false): pre-written code always does what you need. You need -7.6 rounded down, and you guess math.trunc. print(math.trunc(-7.6)) prints -7, which is above -7.6, so it is not rounded down. You may not know how pre-written code works inside.
- Instead: read the documentation. It says trunc rounds toward 0, so -7.6 becomes -7. To round down, use math.floor: print(math.floor(-7.6)) prints -8, the whole number below.
Key words crossword
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Exit quiz
Have a go