Use of a variable in parent loop

Richard Damon Richard at Damon-Family.org
Sun Sep 27 16:57:56 EDT 2020


On 9/27/20 4:42 PM, Christian Gollwitzer wrote:
> Am 26.09.20 um 06:43 schrieb Stephane Tougard:
>> ===PYTHON===
>> #!/usr/local/bin/python
>> if 4 == 4:
>>      name = "Stephane"
>>      print(name)
>>      pass
>>
>> print("Out {}".format(name))
>> ============
>>
>> The exact same code in Python works fine, the variable name is used
>> outside of the if block even it has been declared inside.
>>
>> This does not look right to me. 
>
> I'll try another way of explaining it. You seem to be confused that
> the scope of the variable assignment[*] continues after the if.
> However, look at this:
>
> def f():
>     a=3
>
> f()
> a
>
> NameError
> Traceback (most recent call last)
> <ipython-input-3-60b725f10c9c> in <module>()
> ----> 1 a
>
> NameError: name 'a' is not defined
>
> So the "def f()" obviously introduces local scope, but control
> structures like if and while do not.
>
>     Christian
>
>
> [*] In Python it's called "name binding", but it mostly works like
> variable assignment

Yes, functions and classes have a scope, control structures do not. If
control structures created a scope it would be ugly.

You do need to watch out about the difference between classical
'variables' and pythons name binding when you deal with mutable objects;

For example:

a = []

b = a

a.append(1)

print(b)

give [1] as a and b are bound to the same object, even though you want
to think of them as different variables.

-- 
Richard Damon



More information about the Python-list mailing list