[Tutor] passing variables to functions

Alan Gauld alan.gauld at yahoo.co.uk
Mon Nov 16 11:09:23 EST 2020


On 16/11/2020 15:46, steve10brink1 at comcast.net wrote:
> I always assumed that variables could only be passed to functions 
> via function calls unless they are designated as global. 

Not quite. Functions can see any variables in their surrounding
scope. But if you don't specify them as global inside the function
then the function can only read the variable not modify it
(modifying the variable would create a new local variable).

> How does the variable 'b' get indirectly assigned in the 
> function testVar(a)?  I expected an error.  

> -----------------------------------------------------------
> def testVar(a):
> print(b,a)    #b is from main and not passed thru function call, expect error
> return a

a is a local variable inside the function.
b is global and only being read so the function uses the global b.

> print("Test variables in function.....")
> b = 23.4
> c = testVar(b)

Here the local variable a takes on the same value as b
So the function prints two copies of the same value
and returns the same value that was passed in.

> print("Final: ",c)

So this prints the returned version of a.

> Output:
> 
> Test variables in function.....
> 23.4 23.4
> Final: 23.4

You might find the topic entitled  "What's in a name?"
in my tutorial to be useful.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list