Page 34 - Programming the Raspberry Pi Getting Started with Python
P. 34
Type the following into the Python Shell:
This isn’t really advancing much beyond the 2 + 2 example we tried before. However, this example
does tell us a few things:
• * means multiply.
• / means divide.
• Python does multiplication before division, and it does division before addition.
If you wanted to, you could add some parentheses to guarantee that everything happens in the right
order, like this:
The numbers you have there are all whole numbers (or integers as they are called by programmers).
We can also use a decimal point if we want to use such numbers. In programming, these kinds of
numbers are called floats, which is short for floating point.
Variables
Sticking with the numbers theme for a moment, let’s investigate variables. You can think of a variable
as something that has a value. It is a bit like using letters as stand-ins for numbers in algebra. To
begin, try entering the following:
The equals sign assigns a value to a variable. The variable must be on the left side and must be a
single word (no spaces); however, it can be as long as you like and can contain numbers and the
underscore character (_). Also, characters can be upper- and lowercase. Those are the rules for naming
variables; however, there are also conventions. The difference is that if you break the rules, Python
will complain, whereas if you break the conventions, other programmers may snort derisively and
raise their eyebrows.
The conventions for variables are that they should start with a lowercase letter and should use an
underscore between what in English would be words (for instance, number_of_chickens) . The
examples in Table 3-1 give you some idea of what is legal and what is conventional.
Table 3-1 Naming Variables
Many other languages use a different convention for variable names called bumpy-case or camel-
case, where the words are separated by making the start of each word (except the first one) uppercase
(for example, numberOfChickens). You will sometimes see this in Python example code. Ultimately,
if the code is just for your own use, then how the variable is written does not really matter, but if your
code is going to be read by others, it’s a good idea to stick to the conventions.
By sticking to the naming conventions, it’s easy for other Python programmers to understand your
program.
If you do something Python doesn’t like or understand, you will get an error message. Try entering
the following: