+ 2

Can someone explain this output between global and local variables?

https://code.sololearn.com/cOW90lbYgkjH

27th Jun 2022, 3:49 PM
Trenten Beram
Trenten Beram - avatar
6 Answers
+ 3
I may be completely wrong about this but just as a guess, I believe it's because you called x as a variable rather than a string in the second foo function. So because it is being used in foo when you're trying to see if it's a global variable, it is now also a local variable because it's being "called down" in that space and thus being added to the dictionary for the local function. Because the locals function returns a dictionary with the variable name as the key in string format, and then the value of the same variable as the value of the key. So essentially the result of locals in your second foo function is: { 'x': 1 } You can test it out by adding a print statement after the first one in the second foo function: print(locals())
27th Jun 2022, 4:16 PM
Justice
Justice - avatar
+ 3
Justice you are completely right
27th Jun 2022, 5:43 PM
Oma Falk
Oma Falk - avatar
+ 2
Oma Falk Oh, yay! I'm quite terrible with Python, so I had to do a lot of looking up to try to even make sense of it myself. It was a good challenge and thanks a bunch for the confirmation!
27th Jun 2022, 5:55 PM
Justice
Justice - avatar
+ 2
Slick The first half of the code popped up as a question in a Challenge. I didn't understand how it was False False. Justice Your explanation makes perfect sense. Calling x in foo brings it into foo as a local, even though it was already a local in bar, but not in foo up until it is called.
27th Jun 2022, 6:16 PM
Trenten Beram
Trenten Beram - avatar
+ 1
Lookup "namespaces python" globals() gives you all the names and values of variables in the global namespace. locals() (When called within a function or method) gives you all the names and values of variables WITHIN the function or method, i.e. their local namespace What do you have a question about exactly?
27th Jun 2022, 4:15 PM
Slick
Slick - avatar
- 2
Nh
29th Jun 2022, 3:34 PM
mahesh kote
mahesh kote - avatar