Skip to content

Informatics Practices · Ch 3 — Brief Overview of Python

Assignment Operators

3.6.3

Assignment Operators

A variable is only useful if you can put a value into it — and change that value later. That is exactly what an assignment operator does: it assigns a value to the variable on its left, or changes the value that variable already holds. The variable always sits on the left of the operator, and the value (or expression) being stored sits on the right.

The basic assignment operator =

The plain = takes whatever is on its right and stores it in the variable named on its left. The right side can be a constant, another variable, or any expression:

>>> num1 = 2
>>> num2 = num1
>>> num2
2
>>> country = 'India'
>>> country
'India'

Notice that num2 = num1 copies the value of num1 into num2 — after the assignment, num2 holds 2. Assignment works for every type of value, strings included.

Augmented (shorthand) assignment operators

Programs very often update a variable using its own current value — add something to it, subtract something from it. Python provides shorthand operators that combine an arithmetic operation with assignment in a single step.

Add and assign (+=). It adds the value of the right-side operand to the left-side operand and assigns the result back to the left-side operand. Writing x += y is the same as writing x = x + y:

>>> num1 = 10
>>> num2 = 2
>>> num1 += num2
>>> num1
12
>>> num2
2

num1 grew from 10 to 12, while num2 is untouched — the right-side operand is only read, never changed.

Subtract and assign (-=). It subtracts the value of the right-side operand from the left-side operand and assigns the result back to the left-side operand. x -= y is the same as x = x - y:

>>> num1 = 10
>>> num2 = 2
>>> num1 -= num2
>>> num1
8

The rest of the family. In the same pattern, Python also provides the assignment operators *=, /=, %=, //= and **= — each performs the corresponding arithmetic operation (multiplication, division, modulus, floor division, exponentiation) between the variable and the right-side value, and stores the result back in the variable.

ShorthandEquivalent long form
x += yx = x + y
x -= yx = x - y
x *= yx = x * y
x /= yx = x / y
x %= yx = x % y
x //= yx = x // y
x **= yx = x ** y
Table 3.5Assignment operators in Python
OperatorDescriptionExample (Try in Lab)
=Assigns value from right side operand to left side operand>>> num1 = 2
>>> num2 = num1
>>> num2
2
>>> country = 'India'
>>> country
'India'
+=It adds the value of right side operand to the left side operand and assigns the result to the left side operand.
Note: x += y is same as x = x + y
>>> num1 = 10
>>> num2 = 2
>>> num1 += num2
>>> num1
12
>>> num2
2