Python critique
Octavian Rasnita
orasnita at gmail.com
Sat Dec 11 04:17:53 EST 2010
From: "Steven D'Aprano" <steve+comp.lang.python at pearwood.info>
...
>> 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
Hi Steven,
Thank you for your message. It is very helpful for me.
I don't fully understand the syntax of all these variants yet, but I can see that there are more scopes in Python than I thought, and this is very good.
Octavian
More information about the Python-list
mailing list