Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

2.7 (2 of 3): Using code that others wrote

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

40 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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

WordWhat it meansExample
Pre-written codeCode that somebody else wrote, tested and shared.
User-written codeCode that you write yourself for your own program.
Built-in functionA function that is part of Python. It is always there.len(), max(), round()
LibraryA collection of pre-written code for one kind of job.math, random
importThe Python word that makes a library ready to use.import math
Third-party libraryA library made by another company or group. You install it first.pandas
FunctionA named piece of code that gives back a result.
LicenceThe 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 fromWho wrote itExampleDo you import it?
User-writtenYoudef ticket_cost()No
Built into PythonThe Python teamlen(), print(), round()No
Python libraryThe Python team`math.sqrt()`, `random.randint()`Yes: import math
Third-party libraryAnother grouppandas, matplotlibInstall it, then import it

The cells students fill in are left blank in this preview.

Try it: built-in functions

Code: python
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

Code: python
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 writeIt givesIn words
math.floor(7.6)7Down to the whole number below
math.ceil(7.6)8Up to the whole number above
math.trunc(-7.6)-7Cut off the decimal part
round(7.6)8To the nearest whole number
`math.sqrt(81)`9.0The square root: 9 times 9 is 81
math.pow(2, 5)32.0Five 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

Code: python
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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Fix it: the missing import

Code: python
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

BenefitWhy it helps
Saves timeThe job is already done
Well testedMany people have used it, so there are fewer bugs
Often fasterIt is often quicker than code you would write
Help is easy to findMany programmers use the same code and share answers
Shorter codeThe program is easier to read

The cells students fill in are left blank in this preview.

Drawbacks (bad points) of pre-written code

DrawbackWhy it matters
You may not know how it works insideIt is hard to be sure it does exactly what you need
A bug inside it is hard to fixYou did not write it, so you wait for somebody else to fix it
A third-party library may stop being updatedOld code can stop working or have security holes
It can be bigger than you needIt uses more space and memory
It may have a licenceYou 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.

Code: python
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

  1. 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.
  2. 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'?
  3. 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.
  4. 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.
  5. 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.
  6. 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

Exit quiz

6 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.