= 5
w += 1
w print(w)
When Python sees the operator =
it does the following:
Evaluates the right-hand side (rhs)
The right of the assignment operator can be:
Objects:
age = 21
Variables:
my_cost = your_cost
Expressions:
x = (x + 1) * y
Assigns the resulting object to the variable on the left-hand side (lhs)
Only a single variable is allowed on the left side!
For example,
x + 1 = 2
is WRONG SYNTAX!
Compound assignment operators
- Python and other languages make available a shortcut for performing operations in variables and updating them.
- For example,
is the same as:
= 5
w = w + 1
w print(w)
You can use compound assignment with all operators!
+= 1 # add then assign value
y -= 1 # subtract then assign value
y *= 2 # multiply then assign value
y /= 3 # divide then assign value
y // = 5 # floor divide then assign value
y **= 2 # increase to the power of then assign value
y %= 3 # return remainder then assign value y
Example: what will this expression do?
*= y - 2 x
a