[Tutor] Local variable look up outside the function and method

boB Stepp robertvstepp at gmail.com
Sun May 12 17:46:23 EDT 2019


On Sun, May 12, 2019 at 8:05 AM Arup Rakshit <ar at zeit.io> wrote:
>
> In the following the function, x is reachable outside the scope of foo function.
>
> In [1]: x = 10
>
> In [2]: def foo():
>    ...:     return x
>    ...:
>
> In [3]: print(foo())
> 10

To what the others have said I wish to point out that if x is
reassigned _inside the function_ x's scope is now local inside the
function while x also still has a module scope. Consider:

3.6.8:  x = 10
3.6.8:  def foo():
...     x = 5
...     print("In foo x =", x)
...
3.6.8:  foo()
In foo x = 5
3.6.8:  print("In module scope, x =", x)
In module scope, x = 10


boB


More information about the Tutor mailing list