3 ms·
No, they aren't exactly the same: x = 0 def foo(): x = x + 1 print x UnboundLocalError: local variable 'x' referenced before assig
by yummyfajitas 15y ago
No, they aren't exactly the same:
x = 0
def foo():
x = x + 1
print x
UnboundLocalError: local variable 'x' referenced before assignment
The javascript version works fine.
var x = 0;
var foo = function() { x = x + 1; console.log(x); }
I realize there are ways around this, but they are considered unpythonic. For example:
x = [0]
def foo():
x[0] = x[0] + 1
print x[0]
This works as you'd expect.
- lucian1900 15y agoAs I said, except that bindings are local by default. Python3's nonlocal allows explicit enabling of scheme-like behaviour.