You are familiar with the idea of functions from high school algebra. There you might define a function f
by specifying how it transforms an input into an output, f(x) = 3x + 2
. Then, you might write f(5)
and expect to get the value 17.
Python adopts a similar syntax for invoking functions. If there is a named function foo
that takes a single input (argument), we can invoke a function called add_numbers on the value 5 by writing, add_numbers(5)
.
There are many built-in functions available in Python. Functions are like factories that take in some material, do some operation, and then send out the resulting object.
We’ve defined two functions below. The code is hidden so as not to bother you (yet) with how functions are defined. square
takes a single input argument, and returns that input multiplied by itself. sub
takes two input arguments and returns the result of subtracting the second from the first. Obviously, these functions are not particularly useful, since we have the operators *
and -
available. But they illustrate how functions work. The visual below illustrates how the square
function works
Check the code below, try to call the functions, and subtract 4 from 5. Also, try to square 4.