I 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 (basically, text).
Assign the number 5 to the variable x
:
x = 5
Assign the string “Hello” to the variable y
:
y = "Hello"
Strings need to be surrounded by double or single quotes.
Comments start with a hash:
# This is a comment
y = 'Hello' # You can also use single quotes for strings
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:
z = 10
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:
z = 10
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:
z = 10
elif x == 6: # elif stands for else if
z = 20
else:
z = 100
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.