Functions are blocks of Python code that you write once and can repeat anywhere. It’s a little like being able to write a block of text once, and then paste it whenever you need it.
This article is based on Beginner’s Guide to Coding in issue 53 of The MagPi. Issue 54 of The MagPi has a companion piece on learning object orientated programming with a Raspberry Pi
- Click here to read Beginner’s Guide to Coding in issue 53
- Click here to read Object Orientated Programming in issue 54
See also:
- Programming a Raspberry Pi with Python
- Variables: learn Programming in Python
- Terminal and Python IDLE
- Loops: Using While and For in Python
- Branching: using If and Else in Python
Learning to code in Python is easy, and we've come a long way since the first ‘Hello World’. If you've programs now check for conditions and loop over themselves.
You’re now writing programs that are known as ‘Turing complete’, named after Alan Turing, the father of computer science and artificial intelligence, who hacked the German Enigma code in WWII.
Now we’re going to take things a little further. We’re going to introduce you to functions.
Spotting a function in Python
Python is packed with built-in functions, and you’ve already been using them in your programs. Commands like:
print() len() type()
These are all functions. They’re easy to spot: a small command starting with a lower-case letter and followed by a pair of parentheses ‘()’.
Using functions in Python programming
Let’s take a look at a function called abs(). It stands for ‘absolute’, and returns the absolute value of any number you pass into it (the bit you pass in is called the ‘argument’).
An absolute number is the positive of any number, so if you write abs(-2) you get 2 back. Try this in the Shell:
abs(2) # returns 2 abs(-2) # returns 2
You can store the returned result as a variable:
positive_number = abs(-10)
We find it easier to read a function backwards, from right to left. The value is passed into the parentheses, then the function cranks it and returns a new value. This is passed left and stored into the variable.
Defining a function a Python
The great thing about Python is that you don’t just use the built-in functions: you get to make your own. These are called ‘user-defined functions’.
You create a function using the def keyword, followed by the function name and parentheses. Inside the parentheses, you list the parameters. These are the same as the arguments, only inside the definition they are called ‘parameters’.
def function(parameter): return parameter
This function above doesn’t do anything; it simply accepts a parameter and returns it.
At the end of the function definition is a colon (:). The function code is indented by four spaces, just like a loop or if/else branch.
The code inside the indentation runs when you call the function. Functions typically include a return statement which passes back an expression.
Create a working function in Python
We’re going to create a function that prints the lyrics to Happy Birthday.
Type out the code from the listing below in IDLE 3. Save it as "happy_birthday.py" and then run it (press F5).
def happy_birthday(name): count = 0 while count < 4: if count != 2: print("Happy birthday to you") else: print("Happy birthday dear " + name) count += 1
This function call uses the string ‘Lucy’ as the argument. This string is passed into the function as the parameter and is then available for use in the indented code inside the function.
Try using the function in interactive mode in IDLE. Enter:
happy_birthday("Rob")
And it will display the words to Happy Birthday, but this time use Rob in the lyrics.
Return statements in function in Python
Many functions don’t just run a block of code; they also return something to the function call.
We saw this in abs(), which returned the absolute value of a number. This can be stored in a variable.
In fact, we’re going to recreate the abs() function, so you can see how it’s working behind the scenes.
In maths, you invert a positive/negative value by multiplying a negative number by -1, like this:
10 * -1 = -10 -10 * -1 = 10
We need to create a function that takes a number as a parameter and checks if it’s negative. If so, it multiplies it by -1; if it’s positive, it simply returns the number. We’re going to call our function absolute().
Enter the code in absolute.py. When the function hits either of the return statements, it returns the value of the number (either on its own or multiplied by -1). It then exits the function.
def absolute(number): if number < 0: return number * -1 else: return number
Run the absolute.py code and enter the following in the Shell:
absolute(10) absolute(-10)
Our last program listing is a classic known as ‘FizzBuzz’; as mentioned on page 23, it will help you to understand if, else, and elif.
You also need to know the modulo operator (%) for FizzBuzz. This operator returns the remainder from a division. If you don’t know how modulo works, watch this video.
Now work through the code in fizzbuzz.py.
count = 1 end = 100 while count <= end: if count % 5 == 0 and count % 3 == 0: print("FizzBuzz") elif count % 3 == 0: print("Fizz") elif count % 5 == 0: print("Buzz") else: print(count) count += 1
Looking at Python documentation
You can browse or download a copy of the Python documentation directly from the Python website. Python has a whole bunch of built-in functions. You can view a list of all the built‑in functions on the Python documentation website.
Going further in Python
Here are some resources you will find useful.
GPIO Zero Essentials: This Essentials guide book explains how the GPIO Zero Python module provides access to a bunch of features. These are used to hook up electronics to your Raspberry Pi via the GPIO pins.
FutureLearn: The Raspberry Pi Foundation has two new online training courses: Teaching Physical Computing with Raspberry Pi and Python, and Teaching Programming in Primary Schools.
Learning Python: This tutorial provided by The Raspberry Pi Foundation has files you can download. You download the file, called intro.py, using this command in a Terminal:
wget http://goo.gl/0ZDOdX -O intro.py --no-check-certificate
Open the intro.py file in IDLE; all the instructions are in the file.