How to Update a Python Variable Using Its Own Value

Boxes can be updated — reading the old value to make the new one.

  • Lesson 2 of 5
  • Free
  • Ages 10+
  • 4 hands-on levels
Try this lesson interactivelyReal Python, running in your browser.

The dragon explains

Changing what's remembered

  1. The dragon: A box doesn't have to keep the same thing forever. You can change what's inside it.

  2. The dragon: Here the dragon starts with 50 health.

    example.pyPython 3
    health = 50print(health)
    Output50
  3. The dragon: To heal, you read what's in the box, ADD to it, then save the new number back in the SAME box.

    example.pyPython 3
    health = health + 20
  4. The dragon: Read this right to left: work out health + 20 first (that's 70), THEN put 70 into health.

    example.pyPython 3
    health = health + 20
  5. The dragon: Print it again and you get the new number. The box remembers the change.

    example.pyPython 3
    health = 50health = health + 20print(health)
    Output70
  6. The dragon: One trap to know about: writing health = 20 does NOT add 20. It REPLACES everything with just 20.

    example.pyPython 3
    health = 50health = 20print(health)
    Output20

Quick check

Check your understanding

Say your answer out loud before reading the marked one. Every wrong option is a mistake real beginners make.

  1. Question 1 of 2

    health starts at 30. What does health = health + 10 make it?

    question.pyPython 3
    health = 30health = health + 10print(health)
    • 40Correct
    • 10
    • health + 10

    Why: 30 + 10 = 40, and that 40 gets saved back into health. The box's OLD value is used to make the NEW one.

  2. Question 2 of 2

    gold starts at 5. What does gold = 20 make it — not gold = gold + 20, just gold = 20?

    question.pyPython 3
    gold = 5gold = 20print(gold)
    • 20Correct
    • 25
    • 5

    Why: gold = 20 with no + throws away the old 5 completely and puts 20 in its place. Compare that to gold = gold + 20, which would have kept the 5 and added to it.

In the game

What you'll practice

Four levels in the game: one guided first try with the shape of the answer already there, then three to solve on your own.

  1. 1

    GuidedYour first try

    The dragon's health is 50. It rests by a warm fire and gains 20 health. Show both — what it was, and what it becomes.

  2. +3

    PracticeThree more, on your own

Try it yourself — in real Python.

This lesson is part of a free topic: every lesson in it is free, and no card is needed.

Start this lesson for real

Stuck three times? The game offers the answer — unasked.