Appendix B — Python basics
To assign a value to a variable, use the assignment operator =
. The only variable types we’re interested in are numbers and strings (strings are basically pieces of text).
Assign the number 5 to the variable x
:
= 5 x
Assign the string “Hello” to the variable y
:
= "Hello" y
Strings need to be surrounded by double or single quotes.
Comments start with a hash:
# This is a comment
= 'Hello' # You can also use single quotes for strings y
Python’s comparison operator to test for equality is ==
. The following conditional statement means: If x
equals 5, assign the value 10 to the variable z
.
if x == 5:
= 10 z
Python’s comparison operator to test for inequality is !=
. The following conditional statement means: If x
is not equal to 5, assign the value 10 to the variable z
.
if x != 5:
= 10 z
Note that the conditional statement needs to be followed by a colon. The next line (indicating what to do if x is indeed 5) needs to be indented by a consistent number of spaces (four spaces is recommended). Python does insist on these spaces!
Note that you can have more than just a single condition:
if x == 5:
= 10
z elif x == 6: # elif stands for else if
= 20
z else:
= 100 z
This means: If x
equals 5, assign the value 10 to the variable z
, if x
equals 6, assign the value 20 to the variable z
and in all other cases, assign the value 100 to the variable z
.
In Python, truth values can be expressed using Boolean constants: True
(note the upper-case T
!) indicates that something is true, False
(note the upper-case F
!) that something is false.