Python online tutorial
Part 10: Functions
In programming, a function (sometimes referred to as procedure, routine or method) is a reusable, modular, arbitrarily complex block of code, usually assigned a name and a purpose.
The point of functions is that you can call them from anywhere in your program. Calling a function is the same as invoking it – that is, control flow will run through an entire function defined elsewhere if its name is referenced, optionally passing it certain parameters or arguments. This means you can almost completely eliminate repetition from your code using a combination of loops and functions, obeying one of the basic principles of programming: don’t repeat yourself!
Functions may return a value, and this value may or may not be the result of processing optional inputs.
In Python, you don’t have to worry about visibility or static typing, so it’s generally really easy to define a function. Here’s the code:
A function which takes no arguments:
def function_name():
# Some code here
A function which takes two arguments:
def function_name(param1, param2):
# Some code here
def
is a reserved keyword and stands for define. To be clear, a function definition comprises this keyword, followed by your preferred name (just like with variables, try to use meaningful and representative names, don’t just call it f) and two normal brackets (
and )
, followed by a colon :
Within these brackets you can include as many arguments as you want, named however you want. Python will auto-detect their type. Anything inside a function will need to be indented correctly.
Functions are an extremely important concept not just in Python but in programming, so we’re going to go through a few examples to make sure you can make your own.
You can probably see what’s going on here, but here’s a breakdown:
- Variables
a
andb
are being set to user input (let’s use 5 and 3, just for the example’s sake). - Four functions
add
,sub
,mul
,div
are being defined, with the obvious meanings addition, subtraction, multiplication, division. - When any of these functions are passed two arguments, they will return the result of performing an arithmetic operation on the parameters.
- All four functions are being called within
print
statements, resulting in a program output of:
Let’s take a look at another very small function – one which checks a number is even by using the modulo operation (%
). If the remainder of a division by 2 is equal to 0, we have an even number.
Here’s another similar but slightly more complex function, this time used to check whether a given number is prime or not. I’m using one of the simplest possible algorithms, just checking whether any number up to the square root of the one you’re trying to check is its divisor. Note square root calculation requires the math module, imported at the top.
As with all these examples, you’re encouraged to try and write it yourself and use this page as reference only – remember the best way to learn programming is through practice.
Now you know about the math module, let’s use it in another example, this time with two arguments: given the two legs of a right-angle triangle, calculate the hypotenuse by using Pythagoras’s theorem.
In fact, we can reverse engineer this to create a function that takes 3 parameters and checks if they are a Pythagoras triple:
In-built functions
Before I leave you adrift, you need to know about the difference between user-defined functions (the ones we’ve been doing) and built-in functions (the ones provided by the Python language).
User-defined functions are blocks of code that you define as outlined previously and use anywhere in your program. You cannot use them outside the Python file where they are defined without exporting them. They are a way of providing the programmer with ways to isolate repetitive behaviour and reduce code size.
By contrast, built-in functions are there anywhere you want them. You have probably been using some of them without knowing it – they include such useful entries as print()
, input()
and int()
or str()
. These last two are to do with explicit type conversion, that is, when you want to make sure your input is an integer you would use:
Other extremely useful functions include:
range()
, which will generate a numerical arraylen()
, which will return the number of elements in an arraymap()
, which will apply another function to an entire arrayfilter()
, which will query an array and select only elements satisfying a condition
A full list of built-in functions for Python 3.5 can be found in the official documentation: