learn to code in python

How to learn to program in Python with a Raspberry Pi?

I knew nothing about Python before writing this article 🙂
So why should you read it?
Because I’m pretty good at programming with many other languages, and I start to know the Raspberry Pi well
And also because at the end of this article, you will know how to program in Python 🙂

How to learn to program in Python with a Raspberry Pi?
Python is an accessible language to learn if you already have a basis of logic or algorithmic
However, you will still need to go through the following steps before knowing enough to use it in your projects:

  • Install and discover the Python IDE on Raspberry Pi
  • Check examples of basic syntax to learn 
  • Learn specific things about Python on Raspberry Pi

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

Why Python on Raspberry Pi?

Python introduction

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
A lot of major companies are using Python in their apps, like Google, Facebook, Netflix or Spotify
So it’s not a dead language, learning it now could help you with your career or future projects

Philosophy

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

In the beginning, the Raspberry Pi project was intended 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, Raspbian 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

As I suggested above, it’s not mandatory to have a Raspberry Pi to learn Python
So don’t buy a Raspberry Pi only to learn Python
You could 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 you to use Raspbian Desktop, which comes with anything you need by default
But any distribution can do the work if you prefer another one

You could read my article on how to install Raspbian 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 you to enable SSH and maybe install Xrdp or Vnc to remote connect on 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

Python IDE

On Raspbian Desktop, you’ll get the Thonny Python IDE 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:

thonny python ide

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 happen when you run your script (output or errors)

If you start with Python or programming, I recommend you to work 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:

python myscript.py

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, but for big projects, a powerful interface could be really useful

Most known 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

Hello world

It’s a tradition when you study a new programming language, so let’s start with it
How to display the famous “Hello World!” in Python?

It’s that simple:

print('Hello World!')

In the Thonny IDE, you should get something like this:

hello world in python

As you can see in the Shell area, the script displayed precisely what you entered in the print function parameter
Print is a primary function in Python. They already code it for you, so you can use it directly to display messages
The quotes around the text are a syntax convention, to identify strings in a line of code

Variables

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 do 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:

username='Raspberry'
print('Hello '+username)

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 (string, integer, 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:

variables in python

The input function ask 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 the backslash to say Python that the following apostrophe is not to close the string
You could also use double quotes to avoid this:

input("What's your name? ")

Conditions

Theory

The next step is to learn what are conditions and how to use them in Python
When you create a new program, you’ll often need to do something different depending on a value

  • 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
  • Elseif
  • Else

For if or elseif, you need to define the condition associated and the code to execute if it’s true
This condition is called a boolean statement. It’s always true or false depending on your variables.
Else applies to any other cases, not described in if and elseif

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

Go further

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:

conditions with python

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

Loops

Theory

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

Python

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

While

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 in the while loop because the condition is false
    • It’s the same thing as an if in this case
  • 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:

while loop in python

For

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:

loop for in python

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

Go further

I only gave you the basic to introduce the loops
There are a lot of variable types and functions you could use to fit your needs with loops

Here is some example:

  • 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 loose everyone here, but there is one last thing that you may need with these loops
I suggested creating an infinite loop with a time 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 do 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 is a lot of 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 called “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 shot 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

GPIO Pins

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
And you could control it with a Python script

I’m not an expert in this kind of stuff, so I will give you a short example using the GPIO Zero library

from gpiozero import LED
from time import sleep

led = LED(17)

while True:
    led.on()
    sleep(1)
    led.off()
    sleep(1)

Source: RaspberryPi.org

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

Prerequisites

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)

Related questions

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

Could you use other languages on the Raspberry Pi? If your main goal is to develop things on your Raspberry Pi, there is a lot of other languages you could use on it. All languages able to compile on the ARM chip can be used (C, C++, Scratch). You could also take a look at web languages (HTML, PHP, Javascript)

Conclusion

Here we are
I hope you learned a lot of things about Python and what you could do with it on Raspberry Pi

Coding requires practices.
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

Leave a Comment