Assignment statements
Ok, now that we have finally looked at our ‘atoms’ and ‘molecules’, we can now (finally!) use them to form our first building block - the simple statement building block.
Assignment operator
You should be familiar with this operator by now: =
Repeat after me: “This is not an equality operator. This is an assignment operator.”
Assignment statement
An assignment statement is one of the most frequently occurring simple statement in programming.
In its simplest form, you assign the expression on the right hand side (RHS) to the variable on the left hand side (LHS). Thus, the variable now refers to the object on the right.
Assignment statement \(\Rightarrow\) variable = expression
>>> x = 5
>>> y = (3 >= 4 and x < 10)
More assignment operators
Python also offers many ‘shortcut’ assignment operators: +=
, -=
, *=
, /=
, %=
, //=
, **=
x += y
is equivalent to x = x + y
. The same applies to the others.
Try this out:
>>> x = 5
>>> x += 1
>>> print(x)
>>> x -= 10
>>> print(x)
NOTE to C++ and Java programmers: the increment operator
++
does not exist in Python. Sorry! The philosophy behind Python is that there should preferably only one (obvious) way to do something.
More assignment statement variants
In Python, you can assign the same object to multiple variables at once.
>>> x = y = 558
>>> print(x)
>>> print(y)
You can also perform multiple assignments simultaneously.
>>> x, y, z = 5, 5, 8
>>> print(x)
>>> print(y)
>>> print(z)