Scoping: Is Python and does it matter?

Gordon McMillan gmcm at hypernet.com
Thu May 25 08:31:16 EDT 2000


Quentin Crain <nanotech at europa.com> wrote:

>In Perl one may do something like:
>
>$success=1;
>foreach ... {
>  my($success);         # $success is "local" to this loop
>  . . .
>}
>print $success;         # $success holds whatever value it did before

>In Python, loops have no scope. Correct?

Right - Python does not have a separate scope for code inside a 
loop.

>Does this matter? What do the "experts" do in cases like this?

In this particular case, there's a nice idiom that makes a flag variable 
unnecessary:

for ...:
  if <test for failure>:
    break
else:
  # never hit the break
  print "succeeded!"

- Gordon




More information about the Python-list mailing list