Code zuerst:Namensraum Verständnis in Python mit, wenn und sonst
# case01
def x():
if False:
#x2 = 22
print x1
else:
print x2
if __name__ == '__main__':
if False:
x1 = 1
else:
x2 = 2
x()
case01 ‚s Ausgang:
2
Kein Problem! aber wenn ich Kommentar- #x2 = 22
in if False:
Block und erneut ausführen, wird es eine Fehlermeldung anzeigt:
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-4-e36cb32b2c83> in <module>()
11 else:
12 x2 = 2
---> 13 x()
<ipython-input-4-e36cb32b2c83> in x()
4 print x1
5 else:
----> 6 print x2
7
8 if __name__ == '__main__':
UnboundLocalError: local variable 'x2' referenced before assignment
Wie ich sehe, wird if False:
Block nicht excute, aber warum x2 = 22
eine gewisse Wirkung auf das Skript nehmen i worte?
Meine Python-Version: 2.7.13
Da Zuweisung verwendet wird, um den Gültigkeitsbereich einer Variablen zu bestimmen. Du hast 'x2' zu einem lokalen gemacht. –