Page 38 - Programming the Raspberry Pi Getting Started with Python
P. 38
generated. One for each of the dice. A new variable, total, is assigned to the sum of the two throws.
Next comes the interesting bit: the if command. The if command is immediately followed by a
condition (in the first case, total = = 7). There is then a colon (:), and the subsequent lines will
only be executed by Python if the condition is true. At first sight, you might think there is a mistake in
the condition because it uses == rather than =. The double equal sign is used when comparing items to
see whether they are equal, whereas the single equal sign is used when assigning a value to a variable.
The second if is not tabbed in, so it will be executed regardless of whether the first if is true. This
second if is just like the first, except that we are looking for a total of 11. The final if is a little
different because it compares two variables (throw_1 and throw_2) to see if they are the same,
indicating that a double has been thrown.
Now, the next time you go to play Monopoly and find that the dice are missing, you know what to
do: Just boot up your Raspberry Pi and write a little program.
Comparisons
To test to see whether two values are the same, we use ==. This is called a comparison operator. The
comparison operators we can use are shown in Table 3-2.
Table 3-2 Comparison Operators
You can do some experimenting with these comparison operators in the Python Shell. Here’s an
example:
In this case, we have basically said to Python, “Is 10 greater than 9?” Python has replied, “True.”
Now let’s ask Python whether 10 is less than 9:
Being Logical
You cannot fault the logic. When Python tells us “True” or “False,” it is not just displaying a message
to us. True and False are special values called logical values. Any condition we use with an if
statement will be turned into a logical value by Python when it is deciding whether or not to perform
the next line.
These logical values can be combined rather like the way you perform arithmetic operations like
plus and minus. It does not make sense to add True and True, but it does make sense sometimes to say
True AND True.
As an example, if we wanted to display a message every time the total throw of our dice was
between 5 and 9, we could write something like this:
As well as and, we can use or. We can also use not to turn True into False, and vice versa, as
shown here:
Thus, another way of saying the same thing would be to write the following: