Menu

Libraries

Pre-existing Subprograms

A pre-existing subprogram is a subprogram that has already been written, tested and supplied, so you never write it yourself — you simply call it. Some are built in to Python and are always ready to use, such as len(); others belong to a library, such as random or math.

Why they save you work

  • Time and effort — a job that would take you many lines is done with one call.
  • Already tested — the supplied code has been used and checked by many programmers, so its bugs have been found and fixed. Your own program is more reliable as a result.
  • Shorter, more readable programs — one line says clearly what is happening, so anyone reading your code understands it faster.
  • Fewer errors to find — every routine you don't write is a routine that cannot go wrong inside your program.
  • You can treat it as a black box — you don't need to know how it works inside, only how to call it.

Calling one correctly

Using a pre-existing subprogram takes the same effort however hard its job is, because you only need to know three things: what it does, the arguments it needs and what it returns, if anything. Arguments are the values you place inside the brackets, and you must supply the number the subprogram expects — give it too many or too few and the call stops with an error. The values must also be in the right order and of a sensible type.

Remember that a pre-existing subprogram is only part of a program. You call it from your own code, and you can use it alongside subprograms you devise yourself for the parts that are unique to your solution.

Here len() is called once with the text stored in a variable; the value it returns is stored in characters and then displayed.

# len() is built into Python, so it is ready to call
username = "SpeedyBadger"
characters = len(username)
print(characters)

Output:

12

The next program breaks the rule about arguments: len() expects exactly one value, so passing two stops the program.

# len() needs exactly one argument
total = len("SpeedyBadger", "QuickFox")
print(total)

Output:

TypeError: len() takes exactly one argument (2 given) (line 2)

Practise this