Use both. Use Python 3 until you face a problem that is best solved by reverting to version 2.
Although Python’s most recent version, Python 3, has been around for years, you’ll find that a lot of people still use Python 2. In fact, in the Raspbian distribution, both versions are supplied, and version 2 is just called Python, whereas version 3 is called Python 3. And Python 3 is run by using the command python3
. The examples in this book are written for Python 3 unless otherwise stated. Most will run on both Python 2 and Python 3 without modification.
This reluctance on the part of the Python community to ditch the older version is largely because Python 3 introduced some changes that broke compatibility with version 2. As a result, some of the huge body of third-party libraries developed for Python 2 won’t work under Python 3.
My strategy is to write in Python 3 whenever possible, reverting Python 2 when I need to because of compatibility problems.
For a good summary of the Python 2 versus Python 3 debate, see the Python wiki.
Mu is preinstalled in the latest versions of Raspbian. You will find it in the Programming section of the Main menu (Figure 5-1).
When you first start Mu, you are prompted to select a mode (Figure 5-2).
Select the Python 3 mode and click OK. This opens the Mu editor, so it’s ready for you to start writing some Python.
Let’s try it out. Carefully type the following test into the editor area under the comment “Write your code here :-)”:
for
i
in
range
(
1
,
10
):
(
i
)
This short program will count to 9. Don’t worry how it works for now; all will be explained in Recipe 5.21. Note that when you get to the end of the first line and press Enter, the second line with the print statement should indent automatically (Figure 5-3).
Before we can run the program we need to save it to a file, so at the top of the Mu window, click the Save button and then enter the filename count.py
(Figure 5-4).
Now that the file is saved, run the program by clicking the Run button at the top of the Mu window. This causes the Mu editor screen to split, with the bottom half showing the result of running the program (Figure 5-5).
If you have already followed Recipe 3.22 and downloaded the files accompanying this book, you can open these directly in Mu using the Open button and then navigating to the folder /home/pi/raspberrypi_cookbook_ed3/python, as shown in Figure 5-6. Note that Mu is Python 3 and there are a few Python programs for this book that work only with Python 2, so check the text of the recipe that the code belongs to if you have problems running it from Mu.
Python is unusual for a programming language in that indentation is a fundamental part of the language. Whereas many C-based languages use { and } to delimit a block of code, Python uses the indentation level. So in the preceding example, Python knows that print
is to be invoked repeatedly as part of the for
loop because it is indented four spaces from the left.
When you’re starting out in Python, it’s not uncommon to see an error such as IndentationError: unexpected indent
, which means that something is not indented correctly somewhere. If everything appears to line up, double-check that none of the indents contain tab characters, because Python treats tabs differently.
In selecting Python 3 for our editing mode (Figure 5-2), we ignored the other options for mode. The Adafruit CircuitPython mode allows you to use your Raspberry Pi to program Adafruit’s range of CircuitPython boards, and the BBC micro:bit mode allows you to write MicroPython programs for a BBC micro:bit board. Both of these activities are about using other boards that are not covered in this book; however, it’s good to know that these are an options for using the Raspberry Pi with these microcontrollers.
As well as using Mu to edit and run Python files, you can also take a lower-tech approach by editing files in nano (Recipe 3.7) and then running them from a Terminal session (Recipe 5.4).
Use the Python console, either within Mu or in a Terminal session. The Python console provides a command line a little like that of Raspbian (Recipe 3.3), but instead of entering operating system commands, you can enter Python commands. If you are using Mu (Recipe 5.2), you can access the Python console by clicking the REPL (Read Eval Print Loop) button at the top of the Mu window (Figure 5-7).
Ignoring everything except the bottom of Figure 5-7, you can see that there is a command prompt where you can type Python commands. In this case, I have typed the following:
2
+
2
and reassuringly received the answer:
4
An alternative to using Mu to run individual Python commands is to start a Python 3 console in a Terminal window by typing the command python3
—or to start a Python 2 console, type the command python
.
The >>>
prompt indicates that you can type Python commands. If you need to type multiline commands, then the console will automatically provide a continuation line indicated by three dots. You still need to indent such lines by four spaces, as shown in the following session:
>>>
from
time
import
sleep
>>>
while
True
:
...
(
"hello"
)
...
sleep
(
1
)
...
hello
hello
You need to press Enter twice after your last command for the console to recognize the end of the indented block and run the code.
The Python console also provides a command history so that you can move back and forth through your previous commands using the up arrow and down arrow keys.
When you are finished with the Python console and want to return to the command line, type exit()
.
If you have more than a couple of lines that you want to type in, chances are you would be better off using Mu (Recipe 5.2) to edit and run a file.
Running programs from within Mu (Recipe 5.2) is fine, but sometimes you want to run a Python program from a Terminal window.
Use the python
or python3
command in a Terminal, followed by the filename containing the program you want to run.
To run a Python 3 program from the command line, use a command like this:
$ python3 myprogram.py
If you want to run the program using Python 2, change the command python3
to python
. In both cases the Python program that you want to run should be in a file with the extension .py.
You can run most Python programs as a normal user; however, some you’ll need to run as superuser. If this is the case for your program, prefix the command with sudo
:
$ sudo python3 myprogram.py
In the earlier examples, you need to include python3
in the command to run the program, but you can also add a line to the start of a Python program so that Linux knows it is a Python program. This special line is called a shebang (a contraction of the names of two symbols, “hash” and “interrobang”), and the following single-line example program has it as its first line:
#!/usr/bin/python3 print("I'm a program, I can run all by myself")
Before you can run this directly from the command line, you must give the file write permissions by using the following command (see Recipe 3.14); this assumes the file is called test.py:
$ chmod +x test.py
The parameter +x
means to add execute permissions to the file.
Now you can run the Python program test.py by using the single command:
$ ./test.py I'm a program, I can run all by myself $
The ./ at the start of the line is needed for the command line to find the file.
Recipe 3.25 shows you how to run a Python program as a timed event.
To automatically run a program at startup, see Recipe 3.24.
You assign a value to a name using =
.
In Python, you don’t have to declare the type of a variable; you can just assign it a value using the assignment operator (=), as shown in the following examples:
a
=
123
b
=
12.34
c
=
"Hello"
d
=
'Hello'
e
=
True
You can define character-string constants using either single or double quotes. The logical constants in Python are True
and False
, and they are case sensitive.
By convention, variable names begin with a lowercase letter, and if the variable name consists of more than one word, the words are joined together with an underscore character. It is always a good idea to give your variables descriptive names so that when you come back to your program after a break, you can work out how it works.
Some examples of valid variable names are x
, total
, and number_of_chars
.
You also can assign a variable a value that is a list (Recipe 6.1) or a dictionary (Recipe 6.12).
For more information on arithmetic with variables, see Recipe 5.8.
Use the print
command. You can try the following example in the Python console (Recipe 5.3):
>>>
x
=
10
>>>
(
x
)
10
>>>
Note that the print
command starts a new line to print on.
In Python 2, you can use the print
command without brackets. However, this is not true in Python 3, so for compatibility with both versions of Python, always use brackets around the value you are printing.
To read user input, see Recipe 5.7.
Use the input
(Python 3) or raw_input
(Python 2) command. You can try the following example in the Python 3 console (Recipe 5.3):
>>>
x
=
input
(
"Enter Value:"
)
Enter
Value
:
23
>>>
(
x
)
23
>>>
In Python 2, raw_input
must be substituted for input
in the preceding example.
Python 2 also has an input
function, but that function validates the input and attempts to convert it into a Python value of the appropriate type, whereas raw_input
does the same thing as input
in Python 3 and just returns a string, even if what you typed is a number.
Find more information on Python 2 input
at https://oreil.ly/EhqMt.
Use the +
, -
, *
, and /
operators.
The most common operators for arithmetic are +
, -
, *
, and /
, which are, respectively, add, subtract, multiply, and divide.
You can also group together parts of the expression with parentheses, as shown in the following example, which, given a temperature in degrees Celsius, converts it to degrees Fahrenheit:
>>>
tempC
=
input
(
"Enter temp in C: "
)
Enter
temp
in
C
:
20
>>>
tempF
=
(
int
(
tempC
)
*
9
)
/
5
+
32
>>>
(
tempF
)
68.0
>>>
Other arithmetic operators include % (modulo remainder) and ** (raise to the power of). For example, to raise 2 to the power of 8, you would write the following:
>>>
2
**
8
256
See Recipe 5.7 on using the input
command, and Recipe 5.12 on converting the string value from input
to a number.
The Math
library has many useful math functions that you can use.
If including double or single quotes inside a string, pick the type of quotes that you don’t need to use within the contents of the string itself as the beginning and end markers of the string. For example:
>>>
s
=
"Isn't it warm?"
>>>
(
s
)
Isn
't it warm?
>>>
Sometimes you’ll need to include special characters such as tab or newline inside your string. This requires the use of what are called escape characters. To include a tab, use
, and for a newline, use
. For example:
>>>
s
=
"name
age
Matt
14"
>>>
(
s
)
name
age
Matt
14
>>>
For a full list of escape characters, see the Python Reference Manual.
Use the +
(concatenate) operator.
For example:
>>>
s1
=
"abc"
>>>
s2
=
"def"
>>>
s
=
s1
+
s2
>>>
(
s
)
abcdef
>>>
In many languages, you can have a chain of values to concatenate, some of which are strings and some of which are other types such as numbers, and numbers will automatically be converted into strings during the concatenation. This is not the case in Python, and if you try the following command, you will get an error:
>>>
"abc"
+
23
Traceback
(
most
recent
call
last
):
File
"<stdin>"
,
line
1
,
in
<
module
>
TypeError
:
Can
't convert '
int
' object to str implicitly
You need to convert each component that you want to concatenate into a string before concatenating, as shown in this example:
>>>
"abc"
+
str
(
23
)
'abc23'
>>>
See Recipe 5.11 for more information about converting numbers into strings using the str
function.
A common reason for wanting to convert a number into a string is so you can then concatenate it with another string (Recipe 5.10).
For the reverse operation of turning a string into a number, see Recipe 5.12.
Use the int
or float
Python function.
For example, to convert the string -123
into a number, you could use the following:
>>>
int
(
"-123"
)
-
123
>>>
This will work on both positive and negative whole numbers.
To convert a floating-point number, use float
instead of int
:
>>>
float
(
"00123.45"
)
123.45
>>>
Both int
and float
will handle leading zeros correctly and are tolerant of any spaces or other whitespace characters around the number.
You can also use int
to convert a string representing a number in a number base other than the default of 10 by supplying the number base as the second argument. The following example converts the string representation of binary 1001 into a number:
>>>
int
(
"1001"
,
2
)
9
>>>
This second example converts the hexadecimal number AFF0 into an integer:
>>>
int
(
"AFF0"
,
16
)
45040
>>>
For the reverse operation of turning a number into a string, see Recipe 5.11.
For example, to find the length of the string abcdef
, you would use:
>>>
len
(
"abcdef"
)
6
>>>
The len
command also works on lists (Recipe 6.3).
For example, to find the starting position of the string def
within the string abcdefghi
, you would use:
>>>
s
=
"abcdefghi"
>>>
s
.
find
(
"def"
)
3
>>>
Note that the character positions start at 0 (not 1), so a position of 3 means the fourth character in the string.
If the string you’re looking for doesn’t exist in the string being searched, find
returns the value –1.
The replace
function is used to find and then replace all occurrences of a string (Recipe 5.16).
For example, to cut out a section from the second character to the fifth character of the string abcdefghi
, you would use the following:
>>>
s
=
"abcdefghi"
>>>
s
[
1
:
5
]
'bcde'
>>>
Note that the character positions start at 0 (not 1), so a position of 1 means the second character in the string, and 5 means the sixth; however, the character range is exclusive at the high end. Thus in this example, the letter f is not included.
The [:]
notation is actually quite powerful. You can omit either argument, in which case the start or end of the string is assumed as appropriate. For example:
>>>
s
=
"abcdefghi"
>>>
s
[:
5
]
'abcde'
>>>
and:
>>>
s
=
"abcdefghi"
>>>
s
[
3
:]
'defghi'
>>>
You can also use negative indices to count back from the end of the string. This can be useful in situations such as when you want to find the three-letter extension of a file, as in the following example:
>>>
"myfile.txt"
[
-
3
:]
'txt'
Recipe 5.10 describes joining strings together rather than splitting them.
Recipe 6.10 uses the same syntax but with lists rather than strings.
Another and more powerful way to manipulate strings is described in Recipe 7.23.
The string you’re searching for must match exactly; that is, the search is case sensitive and will include spaces.
See Recipe 5.14 for searching a string without performing a replacement.
Another and more powerful way to manipulate strings is described in Recipe 7.23.
Use the upper
or lower
function as appropriate.
For example, to convert aBcDe
to uppercase, you would use the following:
>>>
"aBcDe"
.
upper
()
'ABCDE'
>>>
To convert it to lowercase, use this:
>>>
"aBcDe"
.
lower
()
'abcde'
>>>
Note that even though upper
and lower
do not take any parameters, they still need a () on the end.
Like most functions that manipulate a string in some way, upper
and lower
do not actually modify the string but rather return a modified copy of the string.
For example, the following code returns a copy of the string s
, but note how the original string is unchanged:
>>>
s
=
"aBcDe"
>>>
s
.
upper
()
'ABCDE'
>>>
s
'aBcDe'
>>>
To change the value of s
to be all uppercase, do the following:
>>>
s
=
"aBcDe"
>>>
s
=
s
.
upper
()
>>>
s
'ABCDE'
>>>
See Recipe 5.16 for replacing text within strings.
Use the Python if
command.
The following example will print the message x is big
only if x
has a value greater than 100:
>>>
x
=
101
>>>
if
x
>
100
:
...
(
"x is big"
)
...
x
is
big
After the if
keyword, there is a condition. This condition often, but not always, compares two values and gives an answer that is either True
or False
. If it is True
, the subsequent indented lines will all be executed.
It is quite common to want to do one thing if a condition is True
and something different if the answer is False
. In this case, the else
command is used with if
, as shown in this example:
x
=
101
if
x
>
100
:
(
"x is big"
)
else
:
(
"x is small"
)
(
"This will always print"
)
You can also chain together a long series of elif
(else if) conditions. If any one of the conditions succeeds, that block of code is executed, and none of the other conditions that follow it are tried.
For example:
x
=
90
if
x
>
100
:
(
"x is big"
)
elif
x
<
10
:
(
"x is small"
)
else
:
(
"x is medium"
)
This example will print x is medium
.
See Recipe 5.19 for more information on different types of comparisons you can make.
Use one of the comparison operators: <
, >
, <=
, >=
, ==
, or !=
.
You used the <
(less than) and >
(greater than) operators in Recipe 5.18. Here’s the full set of comparison operators:
< |
Less than |
> |
Greater than |
<= |
Less than or equal to |
>= |
Greater than or equal to |
== |
Exactly equal to |
!= |
Not equal to |
Some people prefer to use the <>
operator in place of !=
. Both work the same.
You can test these commands using the Python console (Recipe 5.3), as shown in the following exchange:
>>>
1
!=
2
True
>>>
1
!=
1
False
>>>
10
>=
10
True
>>>
10
>=
11
False
>>>
10
==
10
True
>>>
A common mistake is to use =
(set a value) instead of ==
(double equals) in comparisons. This can be difficult to spot because if one half of the comparison is a variable, it is perfectly legal syntax and will run, but it will not produce the result you were expecting.
As well as comparing numbers, you can also compare strings by using these comparison operators, as shown here:
>>>
'aa'
<
'ab'
True
>>>
'aaa'
<
'aa'
False
The strings are compared lexicographically—that is, in the order that you would find them in a dictionary.
This is not quite correct because, for each letter, the uppercase version of the letter is considered less than the lowercase equivalent. Each letter has a value that is its ASCII code, and an uppercase letter has a lower numeric value than the lowercase version of the same letter.
See also Recipes 5.18 and 5.20.
Another and more powerful way to manipulate strings is described in Recipe 7.23.
Use one of the logical operators: and
, or
, or not
.
As an example, you might want to check whether a variable x has a value between 10 and 20. For that, you would use the and
operator:
>>>
x
=
17
>>>
if
x
>=
10
and
x
<=
20
:
...
(
'x is in the middle'
)
...
x
is
in
the
middle
You can combine as many and
and or
statements as you need, and you can also use brackets to group them if the expressions become complicated.
The second parameter in the range
command is exclusive; that is, to count up to 10, you must specify a value of 11.
If the condition for stopping the loop is more complicated than simply repeating the command a certain number of times, see Recipe 5.22.
If you are trying to repeat commands for each element of a list or dictionary, see Recipes 6.7 or 6.15, respectively.
You need to repeat some program code until something changes.
Use the Python while
statement. The while
statement repeats its nested commands until its condition becomes false. The following example will stay in the loop until the user enters X
for exit:
>>>
answer
=
''
>>>
while
answer
!=
'X'
:
...
answer
=
input
(
'Enter command:'
)
...
Enter
command
:
A
Enter
command
:
B
Enter
command
:
X
>>>
Note that the preceding example uses the input
command as it works in Python 3. To run the example in Python 2, substitute the command raw_input
for input
.
If you just want to repeat some commands a certain number of times, see Recipe 5.21.
If you are trying to repeat commands for each element of a list or dictionary, see Recipes 6.7 or 6.15, respectively.
Use the Python break
statement to exit either a while
or for
a loop.
The following example behaves in exactly the same way as the example code in Recipe 5.22:
>>>
while
True
:
...
answer
=
input
(
'Enter command:'
)
...
if
answer
==
'X'
:
...
break
...
Enter
command
:
A
Enter
command
:
B
Enter
command
:
X
>>>
Note that this example uses the input
command as it works in Python 3. To run the example in Python 2, substitute the command raw_input
for input
.
This example behaves in exactly the same way as the example in Recipe 5.22. However, in this case, the condition for the while
loop is just True
, so the loop will never end unless we use break
to exit the loop when the user enters X
.
You can also leave a while
loop by using its condition; see Recipe 5.18.
Create a function that groups together lines of code, allowing it to be called from multiple places.
The following example illustrates how to create and then call a function in Python:
def
count_to_10
():
for
i
in
range
(
1
,
11
):
(
i
)
count_to_10
()
This example defines a function using the def
command that will print out the numbers 1 to 10 whenever it is called:
count_to_10
()
The conventions for naming functions are the same as for variables in Recipe 5.5; that is, they should start with a lowercase letter, and if the name consists of more than one word, the words should be separated by underscores.
The example function is a little inflexible because it can only count to 10. If we wanted to make it more flexible—for example, so it could count up to any number—we could include the maximum number as a parameter to the function, as this example illustrates:
def
count_to_n
(
n
):
for
i
in
range
(
1
,
n
+
1
):
(
i
)
count_to_n
(
5
)
The parameter n
is included inside the parentheses and then used inside the range
command, but not before 1 is added to it.
Using a parameter for the number you want to count up to means that if you usually count to 10 but sometimes count to a different number, you will always have to specify the number. You can, however, specify a default value for a parameter, and hence have the best of both worlds, as shown in this example:
def
count_to_n
(
n
=
10
):
for
i
in
range
(
1
,
n
+
1
):
(
i
)
count_to_n
()
This will now count to 10 unless a different number is specified when you call the function.
If your function needs more than one parameter, perhaps to count between two numbers, the parameters are separated by commas:
def
count
(
from_num
=
1
,
to_num
=
10
):
for
i
in
range
(
from_num
,
to_num
+
1
):
(
i
)
count
()
count
(
5
)
count
(
5
,
10
)
All these examples are functions that do not return any value; they just do something. If you need a function to return a value, you need to use the return
command.
The following function takes a string as an argument and adds the word please to the end of the string:
def
make_polite
(
sentence
):
return
sentence
+
" please"
(
make_polite
(
"Pass the cheese"
))
When a function returns a value, you can assign the result to a variable, or, as in this example, you can print out the result.
To return more than one value from a function, see Recipe 7.3.