Reputation: 11
if you have
def dog(x):
x = 5
x = 7
dog(x)
print(x)
will this print 5 or 7? I can see why it would print 5, since x is reassigned, but when i run it in the terminal, i get 7.
Upvotes: 0
Views: 116
Reputation: 56
When you write x = 7, Python creates an integer object 7 and assigns the name 'x' to it which has a global scope
When you call dog and pass x to it, you are passing a pointer to the integer object 7
Inside dog, when you do x=5, a new name 'x' having a local scope(within the function) points to 5
Since, you are printing x outside the function it prints 7
Note that this only happens for immutable objects (strings, integers, tuples etc) and not mutable objects(Lists, Dictionaries)
If x was a list:
def dog(x):
x.append(5)
x = [7]
dog(x)
print(x)
Output will be [7,5]
Upvotes: 1
Reputation: 16566
That's because of scope.
Using dir
you can see the names in the current scope. Here is some examples to understand the scope concept.
When starting the interpreter:
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
Let's add the x variable:
>>> x=5
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'x']
What is in the scope of a function with an argument:
>>> def dog(y):
... print dir()
...
>>> dog(1)
['y']
As you can see, x
is not in it. So, when you define def dog(x)
, the x
that you use after is only in the scope of the function.
If you want to use the x
define outside dog
, you use the global
keyword:
>>> def dog(y):
... global x
... print dir()
...
>>> dog(1)
['y']
As you can see, x
is still not defined in the scope of dog
. But:
>>> x
5
>>> def dog(y):
... global x
... print x
...
>>> dog(1)
5
More on scoping rules, scopes and namespaces.
Upvotes: 0
Reputation: 107347
Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.
This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope. So when you call dog(x)
, x just in dog
is equal 5
.
for better understanding see below Demo:
>>> def dog(x):
... x = 5
... print x+5
...
>>> x = 7
>>> dog(x)
10
>>> x
7
Upvotes: 5
Reputation: 59186
When you call dog(x)
, you are copying the value of your variable x
into dog
's variable x
. But changing dog
's x
to another value doesn't alter the value of the x
outside the function. They are two separate variables which you have given the same identifier.
Upvotes: 2