Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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 68,457 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 68,457 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