Python Python Collections (2016, retired 2019) Dungeon Game Cartographer

passing arguments from variables defined outside of function

I am a little bit confused here: when Kenneth passes the variable player as an argument into another function, does that function access that variable, even though it was assigned inside of another function? Are variable assignments within functions global?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 58,991 Points

Not sure if I understand the context correctly. If a variable, such as player, is assigned inside some function it is local to that function. While inside that function, if a call to another function is made with player as the argument, then the other function can access player as needed. Neither of these two player references would be considered global.

Python passes arguments "by object reference", it is not actually passing the object or its value between calls.

Post back if you need more help.

Ah, so if you call "function a" within "function b", you can access the variables local to "function a"?

Chris Freeman
Chris Freeman
Treehouse Moderator 58,991 Points

It's a bit more complicated than that. If afunc and bfunc are both defined separately (say, both at a module top level) then the local variables in either are not accessible to the other even if bfunc calls afunc. Calling a function does not alter the hierarchical scope of variables.

However, if afunc is defined inside of bfunc (a function defined inside another function) then, yes, afunc would have access to local variables of bfunc