Hoppy reaches into the darkness to grab the legendary Shadow Cloak. His hand passes right through it.
"It's an illusion," the Gatekeeper whispers. "If the path is not taken, the treasure does not exist."
Existence Precedes Essence
In Python, if a line of code is skipped (for example, inside an if statement that evaluates to False),
it never happens. Any variables defined inside that skipped block are never created.
Trying to use a variable that doesn't exist results in a NameError.
if False: ghost = "Boo!" print(ghost) # Error! 'ghost' is not defined.
Run the code. You will see a NameError because shadow_cloak is defined inside an if block that is skipped (since is_night is False).
To fix this, you have two choices:
- Make the condition
Trueso the block runs. - Or, define
shadow_cloakbefore or outside theifstatement so it always exists.
Ensure Hoppy can wear the cloak!
Advanced TipsWant more? Click to expandClick to collapse
It is a good practice to initialize variables at the top of your function or script, usually to a default value like None or "" or 0.
This ensures that no matter which path the code takes through your if/else maze, the variable always exists when you try to use it later.