Functions in Python
Before continuing, we need to introduce the concept of a function in a high-level language. In high school math, we encounter functions such as sqrt(x), which is an abbreviation of square root and returns the square root of x – for example, sqrt(9) = 3. Computer languages have borrowed the same concept.
Python provides functions that are built into the language. You call a function to perform a specific operation (it’s a bit like subcontracting in the real world) – for example, len()
operates on strings and lists. If you call len(x)
with the list x
, it will return the number of items in that list. Consider the following:
toBuy = len(veg1) # Determine the length of list veg1 (number of items in it)
This takes the list we called veg1
and counts the number of items in it, copying that value to the toBuy
variable. After this operation has been executed, the value of toBuy
will be the integer 3, since there are 3 items...