Libraries
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.
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:
12The 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) Edexcel GCSE Computer Science · Libraries