On Sat, 11 Dec 2010 00:46:41 +0200, Octavian Rasnita wrote: > How narrow are the scopes in Python? > Is each block (each level of indentation) a scope?
Thankfully, no. > If it is, then I > think it is very enough because the other cases can be detected easier > or it might not appear at all in a well-written program. I don't understand what this means. > If it is not, then yes, it is a problem. Why is it a problem? > Can you please tell me how to write the following program in Python? > > my $n = 1; > > { > my $n = 2; > print "$n\n"; > } > > print "$n\n"; > > If this program if ran in Perl, it prints: > 2 > 1 Lots of ways. Here's one: n = 1 class Scope: n = 2 print n print n Here's another: n = 1 print (lambda n=2: n)() print n Here's a third: n = 1 def scope(): n = 2 print n scope() print n Here's a fourth: import sys n = 1 (sys.stdout.write("%d\n" % n) for n in (2,)).next() print n In Python 3, this can be written more simply: n = 1 [print(n) for n in (2,)] print n > I have tried to write it, but I don't know how I can create that block > because it tells that there is an unexpected indent. Functions, closures, classes and modules are scopes in Python. If you want a new scope, create one of those. -- Steven -- http://mail.python.org/mailman/listinfo/python-list