Course outline · 0% complete

0/27 lessons0%

Course overview →

Changing variables

lesson 3-2 · ~12 min · 9/27

Boxes can be refilled

Assigning to an existing variable replaces its contents. The old value is simply gone:

mood = "sleepy"
mood = "focused"
print(mood)

That prints focused.

The most important pattern in all of programming uses a variable's current value to compute its next value:

score = 0
score = score + 10

This looks impossible as math, but remember from lesson 3-1 that = means store, not equals. Python works right side first: look up score (currently 0), add 10, then store the result (10) back into score. Updating a variable step by step like this is how programs count things, total things, and track state. It powers everything in the loops unit coming up.

Code exercise · python

Predict the output before running: score starts at 0, gains 10, then gains 5.

Quiz

After these three lines, what does print(lives) output? lives = 3 lives = lives - 1 print(lives)

Code exercise · python

Your turn. Start followers at 100. On the next line add 25 to it (using followers on both sides of =). On the line after that, double it the same way. Then print it. Expected output: 250.

The shorthand professionals actually type

Updating a variable using its current value is so common that Python has compact operators for it. score += 10 means exactly score = score + 10: take the current value, add 10, store the result back. The same shorthand exists for the other operators: -=, *=, /=.

score = 0
score += 10
score += 5
score -= 3
print(score)

Nothing new is happening — it is the same right-side-first update from the top of this lesson with less typing. You will see += constantly in real code, so learn to read it as "increase by".

Code exercise · python

Predict the final score before running: starts at 0, gains 10, gains 5, loses 3.

Code exercise · python

Your turn, in shorthand. Start steps at 4000. Add 2500 with +=. Then double it with *=. Print the result (expected: 13000).