🎓 A1Learner
🔍

Python Assignment Operators

An assignment operator is a sign that stores a new value in a variable. Short signs like += do the maths and store the answer back.

Updating the long way

Each update repeats the name on both sides of =.

score = 10
score = score + 5
score = score + 5
print(score)

Give a value

One equals sign stores a value in a variable.

score = 10
print(score)

Add to a variable

Read score += 5 as score = score + 5.

score = 10
score += 5
print(score)

Take away, then multiply

Each line updates the value that is already stored.

price = 20
price -= 5
print(price)
price *= 2
print(price)

Divide shortcuts

The sign /= gives a float. The sign //= gives a whole number.

total = 20
total /= 4
print(total)
count = 17
count //= 5
print(count)

A remainder shortcut

This keeps only the minutes left after whole hours.

minutes = 75
minutes %= 60
print(minutes)

Example

balance = 200
print("Start:", balance)
balance += 80
print("Month 1:", balance)
balance += 80
print("Month 2:", balance)
balance += 120
print("Month 3:", balance)

Key points

  • Assignment operator: a sign that stores a new value in a variable.
  • Use = to store a value in a variable.
  • The signs +=, -=, *=, /=, //= and %= each update the variable on the left.
  • Read x += 1 as x = x + 1.
  • Both lines do the same job.
  • Use these shortcuts when a value needs to grow or shrink by one step.

In this example, the balance starts at 200. Python adds 80 for month 1 and the balance is 280. It adds 80 again for month 2 and the balance is 360. It adds 120 for month 3 and the balance is 480.

Note

/= always gives a float, just like /.

A whole number can become a float after /=

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

A variable x holds 8. After x *= 3, what does x hold?