Reputation: 125
I failed this question on a test and I was wondering if someone could help me understand why. The question: Which names occur in the local scope?
a = 3
b = 6
def f(a):
c = a + b
return c
I answered a,b,c, but apparently it's just a and c. Why is b not 'occurring' in the local scope?
Upvotes: 2
Views: 60
Reputation: 46
let me make it clear for you. when you declared 'a' and 'b' above your function they were considered as global variable cause they can be used in any function('a' is being used in function 'f') and 'c' is defined inside the function 'f' so its clearly a local variable but 'b' is not local cause neither its being passed into the function nor being defined its value is used which was declared above in 'c'(here 'b' is acting as global variable). if your function was only 'f()' and 'a' was not passed in then your answer would be 'c'(local variable).Hope it clears
Upvotes: 1
Reputation: 24052
There are global instances of a
and b
, due to their assignments at the file level.
Within function f
, there is a parameter a
which makes that instance of a
local (and independent from the global instance of a
). b
is referenced within f
, but is not assigned to, so b
refers to the global instance of b
. c
is assigned to within f
, so c
is local.
So f
has local instances of a
and c
.
Upvotes: 3