🐸

The Bubble

Python Basicspython-architect-05-scope
Reward: 120 XP
|

Vanishing Gold

Hoppy is practicing Alchemy. Inside the Alchemy Room (Function), he successfully creates a Gold Bar.

But when he steps out of the room to show it off, the gold vanishes into thin air!

def alchemy_room():
  gold = "Gold Bar"
  print("Inside: " + gold) # Works!

alchemy_room()
# print("Outside: " + gold)  # Error! NameError: name 'gold' is not defined

The Magic Bubble (Scope)

Every function behaves like a Bubble. Things created inside (variables) only live inside. Once the function ends, the bubble pops, and everything inside dissolves.

This is called a Local Variable.

To take something out of the bubble, you must explicitly Return it.

Your Mission

1
The Error

Run the current code. You will see an error because Hoppy tries to access secret which is trapped inside the function.

2
Fix the Magic

Modify create_secret to add return secret at the end.

3
Catch the Item

When calling the function, capture the result: my_secret = create_secret().

4
Show Off

Print my_secret. It should work now!

World Constants

Variables defined outside functions are called Global Variables. Like gravity, they exist everywhere and can be seen by everyone.

Breaking the Bubble

If you really need to change a Global Variable from inside a function, you must use the global keyword (e.g., global x). But be careful! This is like poking a hole in your bubble—too many holes make the ship sink.

Suggested Solution
Expand
Solution:
def create_secret():
  secret = "Hoppy loves coding"
  return secret

my_secret = create_secret()
print("The secret is: " + my_secret)
Advanced Tips
Want more? Click to expand

F. Bridge to Reality

  • Bubble = Scope.
  • Why do we need scope? To prevent chaos! If all variables were global, naming conflicts (like two functions both using x) would crash the program. Scope ensures private workspace for each function.
Loading...
Terminal
Terminal
Ready to run...