🐸

The Shadow

Python Basicspython-basics-16-the-shadow
Reward: 100 XP
|

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.
1
The NameError

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

2
Two Solutions

To fix this, you have two choices:

  1. Make the condition True so the block runs.
  2. Or, define shadow_cloak before or outside the if statement so it always exists.
3
The Goal

Ensure Hoppy can wear the cloak!

Advanced Tips
Want more? Click to expand

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.

pymain.py
Loading...
Terminal
Terminal
Ready to run...