Skip to main content

Defining functions in python

Defining functions in python




It is possible, and very useful, to define our own functions in Python. Generally speaking, if you
need to do a calculation only once, then use the interpreter. But when you or others have need to
perform a certain type of calculation many times, then define a function. For a simple example,
the compound command
>>> def f ( x ):
...
return x * x
...
defines the squaring function f (x) = x 2 , a popular example used in elementary math courses. In
the definition, the first line is the function header where the name, f, of the function is specified.
Subsequent lines give the body of the function, where the output value is calculated. Note that
the final step is to return the answer; without it we would never see any results. Continuing the
example, we can use the function to calculate the square of any given input:
>>> f (2)
4
>>> f (2.5)
6.25
The name of a function is purely arbitrary. We could have defined the same function as above,
but with the name square instead of f; then to use it we use the new function name instead of
the old:
>>> def square ( x ):
...
return x * x
...
>>> square (3)
9
>>> square (2.5)

Actually, a function name is not completely arbitrary, since we are not allowed to use a reserved
word as a function name. Python’s reserved words are: and, def, del, for, is, raise, assert,
elif, from, lambda, return, break, else, global, not, try, class, except, if, or, while,
continue, exec, import, pass, yield.
By the way, Python also allows us to define functions using a format similar to the Lambda
Calculus in mathematical logic. For instance, the above function could alternatively be defined in
the following way:
>>> square = lambda x : x * x
Here lambda x: x*x is known as a lambda expression. Lambda expressions are useful when you
need to define a function in just one line; they are also useful in situations where you need a
function but don’t want to name it.
Usually function definitions will be stored in a module (file) for later use. These are indistinguish-
able from Python’s Library modules from the user’s perspective.

Comments