Adjust the Address (Solution)
00:00
If you run the program like it is, you get the output Cookie Cabinet
, Mouse House
and Python Palace
like you explored in one of the former lessons.
00:09
Now, you want line 14 to print Cookie Cabinet
instead of Python Palace
.
00:16
And the challenge now is to do this with one line of code and you’re not allowed to change line 12, but you must add one line inside the function explore_cabinet()
.
00:29
Because of course you could be cheeky and say like, well, I just create a new variable between lines 13 and 14 in front of the print()
function call and set this address to Cookie Cabinet
and call it a day.
00:41
But that’s not what the task is today. Today you need to add one line of code inside of the explore_cabinet()
function. So how do you do that?
00:51
Well, the secret is the global
keyword. With the global
keyword, you can elevate a name from some scope into the global scope. So if you go to the line where you have the docstring with the mouse and press enter for a new line and write global address
, you’re basically saying, I want to address, that’s a coincidence of the words.
01:16
I want to address the address
variable in the global scope instead of the one in the local scope. So in line five, you are not creating a new local scope variable, but you’re overriding the global address
variable by setting global address
in the line before that.
01:36 And that means if you run the code,
01:41
then you can see that the output now is Cookie Cabinet
, Mouse House
and Cookie Cabinet
again. The first print output is the output from line six where you print the address of line five, which is Cookie Cabinet
.
01:55
And the second output Mouse House
is the one in line 10 where you use the variable address
of line eight. And then finally, and that’s the most important part here, once you reach the print()
function call in line 15, the address
variable doesn’t have the value Python Palace
anymore, but Cookie Cabinet
, because after you define address
with Python Palace
in line 13, you are calling the explore_basement()
function where you’re overriding this global address
variable with Cookie Cabinet
and printing it then in line 15, which gives you a third output Cookie Cabinet
.
02:35 So now you have a nice name for your party to take place and hopefully everybody who’s invited will join.
Become a Member to join the conversation.