Why a Python Variable Change Only Affects Later Lines

A change made on one line is real for every line after it, and invisible to every line before it.

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

The dragon explains

Changes stick — but only going forward

  1. The dragon: One more thing about order: a change only counts for the lines AFTER it — never the ones before.

  2. The dragon: The gate opens only for a dragon carrying the key. Walk there first, and — bonk. No key yet.

    example.pyPython 3
    move_right()move_right()
  3. The dragon: Grab the key FIRST, and every line after that knows I'm holding it. Now the gate opens.

    example.pyPython 3
    move_up()grab()move_down()move_right()move_right()
  4. The dragon: When something changes twice, the LAST change is what's true. Two pulls: open, then closed again.

    example.pyPython 3
    move_right()pull_lever()pull_lever()move_right()
  5. The dragon: So: a line only knows what already happened above it — and the most recent change always wins.

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

    No line grabs the key. Where do I end up?

    question.pyPython 3
    move_right()move_right()move_right()move_right()
    • Stuck in front of the gateCorrect
    • On the gold
    • Just past the gate

    Why: In front of the gate. The key is never grabbed, so the gate never opens, and every step after that just bonks.

  2. Question 2 of 2

    The gate starts closed and I pull the lever three times. Is it open at the end?

    question.pyPython 3
    move_right()pull_lever()pull_lever()pull_lever()move_right()move_right()
    • Open — closed, open, closed, open: the last pull winsCorrect
    • Closed — it was closed at the start

    Why: Open. Each pull flips it, and what's true now is whatever the most recent pull did.

In the game

What you'll practice

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

  1. 1

    GuidedYour first try

    The gate only opens for a dragon carrying the key — and the key is up in the nook above the dragon. This code walks straight to the gate without it. Add the lines that fetch the key FIRST.

  2. +2

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