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 definedThe 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
Run the current code. You will see an error because Hoppy tries to access secret which is trapped inside the function.
Modify create_secret to add return secret at the end.
When calling the function, capture the result: my_secret = create_secret().
Print my_secret. It should work now!
Variables defined outside functions are called Global Variables. Like gravity, they exist everywhere and can be seen by everyone.
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 SolutionExpandCollapse
def create_secret():
secret = "Hoppy loves coding"
return secret
my_secret = create_secret()
print("The secret is: " + my_secret)Advanced TipsWant more? Click to expandClick to collapse
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.