Use of a variable in parent loop

Christian Gollwitzer auriocus at gmx.de
Sun Sep 27 16:42:48 EDT 2020


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


More information about the Python-list mailing list