Borrowing ready-made code
A library is a set of ready-made sub-routines that other programmers have written and tested. Python comes with libraries, for example math for number work and random for chance. To use one, you write import at the top of the program, and then call a function with the library name, a dot and the function name, such as math.floor(7.8). Libraries save time because nobody has to write the same code again. The code has usually been tested by many people, so it is likely to work. There are risks too. A library may have mistakes, it may do something different from what you expect, or it may not be maintained. Code from an unknown source could even be harmful. Ask a trusted adult before you add code that you did not write, and always say where code came from.
1import math 2print(math.floor(7.8))
7
| Question | Your own sub-routine | Library function |
|---|---|---|
| Who wrote it? | you | other programmers |
| Has it been tested by many people? | only by you | usually yes |
| Time to write | longer | none: you import it |
| Can you see exactly how it works? | yes | not always |
| Benefits | Risks |
|---|---|
| saves time | may contain mistakes |
| already tested | may not do exactly what you need |
| same code used by many people | unknown code from an untrusted source could be harmful |
| programs are shorter | you must trust the author, so ask a trusted adult |
Library cards (no computer). Make a card for each of four imaginary library functions, for example round_up, pick_number, add_tax and shout. On each card write the name, what value it needs (the parameter), what it gives back (the return value) and who wrote it. Choose a small problem, such as working out the price of 6 notebooks including tax. Decide which cards you would use and in which order. Then write one benefit and one risk of using ready-made cards. Swap cards with a partner and plan a different problem. If you have a computer or tablet, ask an adult to show you where Python’s math library is described.