Learning Python is an important step to use a Raspberry Pi efficiently. But it’s not straightforward to learn if you start from scratch.
I’m a web developer, so I’m good with coding, and I’ll share with you some tips for getting started quickly with Python.
The Raspberry Pi system includes an IDE to code in Python, the basic libraries are pre-installed, and the GPIO pins are perfect to experiment. There a few steps to follow to understand the Python code, but it’s not so complicated.
I will try to write this article to help both beginners in programming and beginners in Python (but who already know other languages).
It’s up to you to adapt the rhythm of reading to your level. If you already code with other languages, the snippets may be enough to catch the syntax.
By the way, if you are really interested in improving your skills on Raspberry Pi, I highly recommend to check out my e-book here. It’s a 30-days challenge from beginner to master, with step-by-step tutorials and many projects to practice along the way.
Link between Python and Raspberry Pi
Python is a high-level language to program all kinds of software (like C, C++ or other languages).
It’s similar to a bash script because you can run it directly.
Most of the Python source code have a .py filename extension, and you can run it using “python file.py”.
The conception of the Python language started in the 80s, and it’s still an active language, with a big community.
Most major companies are using Python in their apps, like Google, Facebook, Netflix or Spotify.
So, it’s not an outdated language, learning it now could help you with your career or future projects.
In fact, it’s one of the most widely used Language in the world:
Find more statistics at Statista
Tim Peters wrote the Python philosophy in twenty aphorisms like these:
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts.
It gives you an idea of what to expect when using Python.
One of the main goals is to keep it fun to use.
You could find the complete list on the official Python website.
Python and the Raspberry Pi
The goal of the Raspberry Pi Foundation is to help young students to learn how to code.
The Raspberry Pi foundation sent a lot of Raspberry Pi in the UK schools, and also created clubs to teach children how to code.
As you may have noticed, Raspberry Pi OS comes with Python by default and with a complete IDE already installed (in the Desktop version).
So if you have a Raspberry Pi and want to learn how to program, using Python is the natural way to do this.
By the way, it’s not mandatory to have a Raspberry Pi to learn Python. So don’t buy a Raspberry Pi only to learn Python.
You can do the same on any operating system, as Python is a cross-platform language.
You only need to find an editor to fit your needs on your current operating system.
Install your operating system
If you don’t have already done this, you first need to install an operating system on your Raspberry Pi.
I recommend using Raspberry Pi OS Desktop, which comes with anything you need by default.
But any distribution can do the work if you prefer another one.
You can read my article on how to install Raspberry Pi OS on a Raspberry Pi if you don’t know how to do this.
If you don’t have a good workspace with your Raspberry Pi, I recommend enabling SSH and maybe installing Xrdp or VNC to remotely connect to your Raspberry Pi.
It may be more comfortable to read this article and to type code from your usual computer.
Once everything is fine with your installation, go to the next step.
Software to code in Python
You have two main possibilities to use Python on a Raspberry Pi.
On Raspberry Pi OS Desktop, the Thonny Python IDE is installed by default.
It’s a basic interface to write your code, save and run it, and see what happen in an integrated shell output.
Here is what you’ll get on the first start:
This clean interface is intuitive.
In the top menu, you’ll find the most useful icons for creating a file, save or load it, launch it, as well as shortcuts for formatting the code.
Advanced actions are all hidden in the menu, to not disturb beginners.
The first text area is for your script and the second is a console to see what happens when you run your script (output or errors).
If you are just starting with Python or programming, I recommend working with this tool.
You’ll save time and, if you need something else later, that’s not a big deal to switch to another editor.
Any text editor
As I said in the introduction, Python can be run with a command like this:
So, you can create the script file with any editor from nano to Eclipse if you want.
For beginners, I think that this will only add other issues and questions, but for big projects, a powerful interface could be really useful.
The most popular interfaces to code in Python are :
- Code editors like Sublime Text, Visual Studio Code or Notepad++
- IDEs like Eclipse with PyDev, PyCharm or Spyder
- Specific Python editors like SPE
Any editor can do the job. You have the choice 🙂
Basic samples to learn
Let’s start with your first lines of code.
On this part, you’ll learn the basic language syntax of Python.
This is not specific to the Raspberry Pi. It will work anywhere.
This is a tradition when you study a new programming language, so we need to start with this.
How to display the famous “Hello World!” in Python?
It’s that simple:
In the Thonny IDE, you should get something like this:
As you can see in the Shell area, the script displayed precisely what you put in the print function parameter.
Print is a primary function in Python that displays some text. They already code it for you, so you can use it directly.
The quotes around the text are a syntax convention, to identify strings in a line of code.
In any language, variables are used to store values locally and temporarily.
For example, you could ask the username at the beginning of your script and display it later in your code.
To achieve this, you need to define a variable and use it to store the username in it.
In Python, here’s how this example looks like:
On the first line, we set the username variable with the ‘Raspberry’ string.
In most languages, you first need to create a variable, setting its type (a string, an integer, an array), before using it in the code.
In Python, there is no command to declare a variable. You can use it directly.
On the second line, we use the same print function as seen before.
I introduce a new syntax element with the ‘+’, used to concatenate strings.
When we ask Python to display ‘Hello ‘+username, it will display ‘Hello Raspberry’ instead.
The variable value is used as another string to display, stuck to the first part.
If you are following me, you should have noticed that this is not exactly the example I gave 🙂
Here is how to ask the username and display dynamically depending on the user response:
The input function asks for an input value to the user and set it in the username variable.
Then you can display the variable as in the previous example.
We use a backslash to say Python that the following apostrophe is not to close the string.
You can also use double quotes to avoid this:
input("What's your name? ")
The next step is to learn what are conditions and how to use them in Python.
A condition allows you to do something different depending on an expression (a variable value for example).
- If the input string is empty, display an error
- If the button is pressed, turn on the LED
- If the password is correct: do the action, else: ask again
In most languages there are three conditions you can use, in this order:
- If : first case
- Elseif : other cases, tested only if the previous cases are all false
- Else : default case if none of the conditions are true
For if or elseif, you need to define the condition associated and the code to execute if it’s true.
These conditions are called boolean statements. They are always true or false depending on your variables.
Else applies to any other cases, not described in if and elseif.
It will be easier to understand with an example in Python.
In Python, you’ll find something similar, except that elseif is called elif
value=input("Value?") if value == 'a': print("a") elif value == 'b': print("b") else: print("Anything else")
For each condition, the syntax is to use the main word (if, elif or else).
For if and elif you’ll find the boolean statement just after (value == “a”). It’s true if the value contains a false otherwise.
The else doesn’t have any condition, it will execute the code below if the value is anything else than a or b.
The “:” at the end of the line is here to indicate the end of the condition.
When you run this code, you can try to enter a, b or any other value when asked and see what happen.
Unlike the example in the previous paragraph, the display will be different depending on the input value you type.
The “elif” and “else” statements are optional.
If you have only one value to test, you could remove one part, like this:
value=input("Password?") if value == '1234': print("Access granted") else: print("Try again")
If you have more than two values to test you can add as much elif as necessary:
value=input("Value?") if value == 'a': print("a") elif value == 'b': print("b") elif value == 'c': print("c") elif value == 'd': print("d") else: print("Error")
When the code below the matched condition ends, the script will continue after the end of the conditional group.
It will not try the other conditions.
In Thonny you should get something like that:
If you start today learning code, take time to digest this because the following is even more complicated 🙂
It’s a logic to learn, more than a language.
Don’t hesitate to make some tests on your side to be sure you understand this part.
The last concept I want to introduce is the loops.
Loops are a way to execute the same code portion several times.
Let’s take some examples:
- As long as the password entered is not the good one, ask it again and again
- For each file in a folder, do something
- Infinite loop: Do the same thing every X minutes
This concept will allow us to have a dynamic code depending on something else.
It also avoids having several identical pieces of code, or to execute the script too often.
In Python, you have only two ways to create loops:
- For: Execute the code for each item in a sequence (list, range, string, …)
- While: As long as your condition is true, the code will be executed
For those who know it from another language, there is no “foreach” instruction in Python. You have to use “for” instead.
I will start with “while” because it’s very close to the conditions we have seen just before.
As I said, it will run your code until the boolean statement becomes false.
Here is the same password example, with a loop:
password=input("What's your password?") while password!="1234": print("Error") password=input("What's your password?") print("Password correct")
We already know almost anything in this code.
We start by asking the password.
Then there are two cases:
- The password is correct:
- The script will never enter the while loop because the condition is false
- In this case, it’s the same thing as an if
- The password is incorrect:
- The script will enter the while loop
- It displays an error and asks again for the password
- After that, the script come back to the “while” word, and try again the same boolean condition
- This loop will never stop until the password is correct
Don’t forget to change the variables in the while condition inside the loop. Otherwise, you will create an infinite loop.
The execution of this script in Thonny with two password errors look like this:
For is something a little different.
You’ll use it for an already defined sequence of things, not depending on the user entry or something that evolves over time.
Here is one example:
alphabet= ["a", "b", "c"] for letter in alphabet: print(letter)
On the first line, I introduce a new type of variables. It’s a list of elements (like an array in other languages).
The “for” syntax creates a new variable with the current item of your list (I call it “letter”).
Then you can use this variable in the loop code.
On Thonny you will get this:
As you can see, the code is executed three times, once for each letter.
I use only one line, but there is no limit, there could be 300 lines.
I only gave you the basic to introduce the loops.
There are many variable types and functions you could use to fit your needs with loops.
Here are some examples:
- range(0,10): to execute a loop from 0 to 10
- range(0,100,3): to execute a loop from 0 to 100 but incrementing x by 3 each time
- string: to browse letters from a string
You could find more information on the official Python wiki.
I don’t want to lose everyone here, but there is one last thing that you may need with these loops.
I suggested creating an infinite loop with a clock in the introduction, but I didn’t explain to you how to wait a certain amount of time at each run.
Here is how to do this:
import time; password=input("What's your password?") while password!="1234": print("Error") time.sleep(10) password=input("What's your password?") print("Password correct")
As you can see it’s the same example as above with the password.
We introduce here a 10s wait time before trying another password (for security reasons for example).
To code this we need to use a Python library and call it with the import syntax.
This library will provide you with new functions you can use in your script.
And so, we use time.sleep in the loop, to wait for an extra 10s before asking for a new password.
There are many Python libraries you can use like this one.
We’ll see some of them in the next paragraph, but don’t forget to search for them before making a code that someone already made.
Code for Raspberry Pi
Ok, now that we have seen or reviewed the basics of Python programming, we’ll be able to focus on our main goal: the Raspberry Pi projects we could do with some basic Python skills
Control your camera
If you have a camera on the camera port of your Raspberry Pi, you can try to control it with Python.
There is a library named “picamera” that allows you to use your camera in a Python script.
Here is a basic sample including the main functions:
import picamera with picamera.PiCamera() as camera: camera.start_preview() camera.capture('/home/pi/Images/python.jpg') camera.stop_preview()
This script will take one shot each time you run it, and save the picture in the specified folder.
Don’t forget to import the picamera library at the beginning of the script.
Then you can use start_preview to start the camera, capture to shoot the picture and stop_preview to stop the camera.
I made an entire article about cool things to do with a camera on Raspberry Pi.
Feel free to read it if you want other examples.
Another great feature from the Raspberry is the GPIO pins you’ll find on the board.
These pins allow you to create an electronic circuit with components like LEDs, buttons or whatever.
You can control GPIO pins and circuits in Python.
I’m not an expert in that kind of stuff, so I will give you a short example using the GPIO Zero library. And if you want to learn more, you can check my dedicated guide on the topic.
from gpiozero import LED from time import sleep led = LED(17) while True: led.on() sleep(1) led.off() sleep(1)
At the beginning of the script, we need to import two libraries (gpiozero for LED management and time for the sleep function we saw before).
Then we set the GPIO pin to use for the next stage of the script.
And finally, we create an infinite loop which makes the LED blink every second.
This entire example doesn’t use many more concepts than those seen in this article.
There are other libraries similar to gpiozero you could use, like RPI.GPIO, pigpio or wiringPi.
If you start, gpiozero may be simpler to understand how it works.
To start on this kind of electronic projects, you’ll need some components to create your circuit.
I recommend you to get a kit like this one on Amazon with all the needed stuff.
Even if you think that there are too many things for you in it, it’s so cheap that you can take it directly.
You could use it on your next projects 🙂
If you don’t have a Raspberry Pi yet, Canakit also offers a kit with the Raspberry Pi and some components to get started with electronic circuits
It might be a good deal to start (check the price on Amazon).
Why is Python used in Raspberry Pi? Python is the favorite language on Raspberry Pi because everything is already included. As soon as you install your system, you get all pythons prerequisites installed, an IDE and all needed libraries for your Raspberry Pi.
Should you learn Python as a first coding language? There are more or less complicated languages to master. Python is one of the easiest to learn. So, it’s not a bad choice. You’ll also learn the basics of algorithmic that will help you switch to another language next.
Here we are.
I hope you learned many things about Python and what you can do with it on Raspberry Pi.
Coding requires practice.
If you start learning how to program today, you’ll not be able to make something perfect the first time.
You have to try things, learn other and especially do not stop there.
If you do nothing in Python in the two next weeks, you will forget everything :/
If you need more ideas to experiment with your new Python skills, Hackster has a good list on this page.