Python is a wonderful and powerful programming language that's easy to use (easy to read and write) and with Raspberry Pi lets you connect your project to the real world.
Python syntax is very clean, with an emphasis on readability and uses standard English keywords. Start by opening IDLE from the desktop.
The easiest introduction to Python is through IDLE, a Python development environment. Open IDLE from the Desktop or applications menu:
IDLE gives you a REPL (Read-Evaluate-Print-Loop), which is a prompt you can enter Python commands into. Because it's a REPL, you even get the output of commands printed to the screen without using print
.
Note: two versions of Python are available — Python 2 and Python 3. Python 3 has was first released in 2008 and Python 2 development ended with 2.7, which was released in 2010. Python 3 is recommended, but Python 2 is available for legacy applications which do not support Python 3 yet.
You can use variables if you need to but you can even use it like a calculator. For example:
>>> 1 + 2
3
>>> name = "Sarah"
>>> "Hello " + name
'Hello Sarah'
IDLE also has syntax highlighting built in and some support for autocompletion. You can look back on the history of the commands you've entered in the REPL with Alt + P
(previous) and Alt + N
(next).
Hello world in Python:
print("Hello world")
Simple as that!
Some languages use curly braces {
and }
to wrap around lines of code which belong together, and leave it to the writer to indent these lines to appear visually nested. However, Python does not use curly braces but instead requires indentation for nesting. For example a for
loop in Python:
for i in range(10):
print("Hello")
The indentation is necessary here. A second line indented would be a part of the loop, and a second line not indented would be outside of the loop. For example:
for i in range(2):
print("A")
print("B")
would print:
A
B
A
B
whereas the following:
for i in range(2):
print("A")
print("B")
would print:
A
A
B
To save a value to a variable, assign it like so:
name = "Bob"
age = 15
Note that data types were not specified with these variables, as types are inferred, and can be changed later.
age = 15
age += 1 # increment age by 1
print(age)
This time I used comments beside the increment command.
Comments are ignored in the program but there for you to leave notes, and are denoted by the hash #
symbol. Multi-line comments use triple quotes like so:
"""
This is a very simple Python program that prints "Hello".
That's all it does.
"""
print("Hello")
Python also has lists (called arrays in some languages) which are collections of data of any type:
numbers = [1, 2, 3]
Lists are denoted by the use of square brackets []
and each item is separated by a comma.
Some data types are iterable, which means you can loop over the values they contain. For example a list:
numbers = [1, 2, 3]
for number in numbers:
print(number)
This takes each item in the list numbers
and prints out the item:
1
2
3
Note I used the word number
to denote each item. This is merely the word I chose for this - it's recommended you choose descriptive words for variables - using plurals for lists, and singular for each item makes sense. It makes it easier to understand when reading.
Other data types are iterable, for example the string:
dog_name = "BINGO"
for char in dog_name:
print(char)
This loops over each character and prints them out:
B
I
N
G
O
The integer data type is not iterable and trying to iterate over it will produce an error. For example:
for i in 3:
print(i)
will produce:
TypeError: 'int' object is not iterable
However you can make an iterable object using the range
function:
for i in range(3):
print(i)
range(5)
contains the numbers 0
, 1
, 2
, 3
and 4
(five numbers in total). To get the numbers 1
to 5
(inclusive) use range(1, 6)
.
You can use functions like len
to find the length of a string or a list:
name = "Jamie"
print(len(name)) # 5
names = ["Bob", "Jane", "James", "Alice"]
print(len(names)) # 4
You can use if
statements for control flow:
name = "Joe"
if len(name) > 3:
print("Nice name,")
print(name)
else:
print("That's a short name,")
print(name)
To create a Python file in IDLE, click File > New File
and you'll be given a blank window. This is an empty file, not a Python prompt. You write a Python file in this window, save it, then run it and you'll see the output in the other window.
For example, in the new window, type:
n = 0
for i in range(1, 101):
n += i
print("The sum of the numbers 1 to 100 is:")
print(n)
Then save this file (File > Save
or Ctrl + S
) and run (Run > Run Module
or hit F5
) and you'll see the output in your original Python window.
You can write a Python file in a standard editor like Vim, Nano, or LeafPad, and run it as a Python script from the command line. Just navigate to the directory the file is saved in (use cd
and ls
for guidance) and run with python3
, e.g. python3 hello.py
.
The standard built-in Python shell is accessed by typing python3
in the terminal.
This shell is a prompt ready for Python commands to be entered. You can use this in the same way as IDLE, but it does not have syntax highlighting or autocompletion. You can look back on the history of the commands you've entered in the REPL by using the Up/Down keys. Use Ctrl + D
to exit.
IPython is an interactive Python shell with syntax highlighting, autocompletion, pretty printing, built-in documentation, and more. IPython is not installed by default. Install with:
sudo pip3 install ipython
Then run with ipython
from the command line. It works like the standard python3
, but has more features. Try typing len?
and hitting Enter
. You're shown information including the docstring for the len
function:
Type: builtin_function_or_method
String Form:<built-in function len>
Namespace: Python builtin
Docstring:
len(object) -> integer
Return the number of items of a sequence or mapping.
Try the following dictionary comprehension:
{i: i ** 3 for i in range(12)}
This will pretty print the following:
{0: 0,
1: 1,
2: 8,
3: 27,
4: 64,
5: 125,
6: 216,
7: 343,
8: 512,
9: 729,
10: 1000,
11: 1331}
In the standard Python shell, this would have printed on one line:
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729, 10: 1000, 11: 1331}
You can look back on the history of the commands you've entered in the REPL by using the Up/Down keys like in python
. The history also persists to the next session, so you can exit ipython
and return (or switch between v2/3) and the history remains. Use Ctrl + D
to exit.
Some Python packages can be found in the Raspbian archives, and can be installed using apt, for example:
sudo apt update
sudo apt install python-picamera
This is a preferable method of installing, as it means that the modules you install can be kept up to date easily with the usual sudo apt update
and sudo apt upgrade
commands.
Not all Python packages are available in the Raspbian archives, and those that are can sometimes be out of date. If you can't find a suitable version in the Raspbian archives, you can install packages from the Python Package Index (known as PyPI).
To do so, install pip:
sudo apt install python3-pip
Then install Python packages (e.g. simplejson
) with pip3
:
sudo pip3 install simplejson
Read more on installing software in Python here.
The official Python Package Index (PyPI) hosts files uploaded by package maintainers. Some packages require compilation (compiling C/C++ or similar code) in order to install them, which can be a time-consuming task, particlarly on the single-core Raspberry Pi 1 or Pi Zero.
piwheels is a service providing pre-compiled packages (called Python wheels) ready for use on the Raspberry Pi. Raspbian Stretch is pre-configired to use piwheels for pip. Read more about the piwheels project at www.piwheels.org.