[Tutor] passing variables to functions

Mats Wichmann mats at wichmann.us
Mon Nov 16 11:08:00 EST 2020


On 11/16/20 8:46 AM, steve10brink1 at comcast.net wrote:
> Hi,
> 
> I always assumed that variables could only be passed to functions via function calls unless they are designated as global.  So I was suprised that this code works without any errors.  How does the variable 'b' get indirectly assigned in the function testVar(a)?  I expected an error.  I am using python3 version 3.5.3.
> 
> Code:
> -----------------------------------------------------------
> def testVar(a):
> print(b,a)    #b is from main and not passed thru function call, expect error
> return a
> 
> print("Test variables in function.....")
> b = 23.4
> c = testVar(b)
> print("Final: ",c)
> 
> -----------------------------------------------------------
> Output:
> 
> Test variables in function.....
> 23.4 23.4
> Final: 23.4

"That's how it works" :)

If there's not a value in the local scope (inside the function 
definition), Python picks it from the global scope.  On the other hand, 
if you were assigning to b in the function, Python would create b in the 
local scope if you did not use the "global" statement.

It might be useful to think of it as a set of dictionaries, since in 
most cases that's what it is:

 >>> b = 23.4
 >>> print(globals())
{'__name__': '__main__', '__doc__': None, '__package__': None, 
'__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': 
None, '__annotations__': {}, '__builtins__': <module 'builtins' 
(built-in)>, 'b': 23.4}
 >>> def testVar(a):
...     c = 10
...     print(locals())
...
 >>>
 >>> testVar(b)
{'a': 23.4, 'c': 10}
 >>>

The local scope in testVar got the var 'c' from the direct assignment 
and the var 'a' from the function argument; if there where a reference 
to 'b', it wouldn't find it in the locals dict so it would fall back to 
the globals, and find it from there.




More information about the Tutor mailing list