Assignments

When Python sees the operator = it does the following:

  1. 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

  2. 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,
w = 5
w += 1
print(w)

is the same as:

w = 5
w = w + 1
print(w)

You can use compound assignment with all operators!

y += 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

Example: what will this expression do?

x *= y - 2

a