From: Navkirat Singh on
Hi,

I had another question:

What is the scope of a parameter passed to a function? I know its a very basic question, but I am just sharpening my basics :)

def func_something(x)

return print(x+1);

Does x become a local variable or does it stay as a module scoped variable?

Though I think its local, but just want to be sure.

Thanks,
Nav
From: Chris Rebert on
On Wed, Jul 28, 2010 at 7:00 PM, Navkirat Singh <navkirats(a)gmail.com> wrote:
> Hi,
>
> I had another question:
>
> What is the scope of  a parameter passed to a function? I know its a very basic question, but I am just sharpening my basics :)
>
> def func_something(x)
>
>        return print(x+1);
>
> Does x become a local variable or does it stay as a module scoped variable?
>
> Though I think its local, but just want to be sure.

Yes, it's indeed local. Also, you may wish to instead direct similar
basic questions to the Python Tutor mailinglist in the future:
http://mail.python.org/mailman/listinfo/tutor

Cheers,
Chris
--
http://blog.rebertia.com
From: Steven D'Aprano on
On Thu, 29 Jul 2010 07:30:34 +0530, Navkirat Singh wrote:

> Hi,
>
> I had another question:
>
> What is the scope of a parameter passed to a function? I know its a
> very basic question, but I am just sharpening my basics :)
>
> def func_something(x)
> return print(x+1);
>
> Does x become a local variable or does it stay as a module scoped
> variable?
>
> Though I think its local, but just want to be sure.


Yes, x is local.

However, be careful that Python does not make a copy of arguments passed
to functions. So the local name refers to the same underlying object as
the global name, and *modifications* to the *object* will be seen
everywhere. But *reassignments* to the *name* are only seen locally.



def test(local_name):
print(local_name)
local_name = 2
print(local_name)
print(global_name)

global_name = 1
test(global_name)

=> prints 1, 2, 1.



def test(local_name):
print(local_name)
local_name.append(2)
print(local_name)
print(global_name)

global_name = [1]
test(global_name)

=> prints [1], [1, 2], [1, 2].


--
Steven