So this "natural" solution in Perl (that is w/o flag variable) isn't possible in Python
N: for my $n (2 .. 99) { for my $x (2 .. $n - 1) { next N if 0 == $n % $x; } say $n, ' is a prime number'; }
Looking at a one to one translation of the flow, it bugs me that the "NOT_PRIME" part is executed after the "PRIME" part, which is quite strange in my eyes
for my $n (2 .. 99) { for my $x (2 .. $n - 1) { goto NOT_PRIME if 0 == $n % $x; } PRIME: say $n, ' is a prime number'; NOT_PRIME: }
So to separate code which doesn't belong to the py-else branch one needs to put it into the loop into the py-if branch
so the logic of this Perl code with flag-var prime
for my $n (2 .. 99) { my $prime = 1; for (2 .. $n-1) { $prime = 0, last unless $n % $_; } if ($prime) { print $n, " is "; } else { print $n, " is not "; } print "a prime number\n"; }
translates to
for my $n (2 .. 99) { for my $x (2 .. $n - 1) { if (0 == $n % $x) { # py-if branch print $n, " is not "; goto BREAK; # py-break } } print $n, " is "; # py-else branch BREAK: print "a prime number\n"; }
I think now the motivation to call this statement "else" it's better understandable. But the py-docs do not seem to provide any such motivation.
Maybe it's a matter of practice, but I rather prefer the ability to have Perl labels and loop controls like next or last to address them.
And Perl's goto still gives me the freedom to emulate any python code in a 1-to-1 translation. And the naming of the label in Perl gives me additional freedom to clarify the code! ¹
Python OTOH can't emulate labels or Perl's control flow and needs to redesign the code when migrated.
See also this SO- discussion http://stackoverflow.com/questions/438844/is-there-a-label-goto-in-python for how quirky and complicated py-workarounds can become...
Cheers Rolf
( addicted to the Perl Programming Language)
¹) Please note that I named the "BREAK:"-label as "NOT_PRIME:" in my first post, thats very self-commenting and easier to understand than simply "else:"
In reply to Re^2: Perl vs. Python (for/else idiom analyzed)
by LanX
in thread Perl vs. Python for prime numbers
by Anonymous Monk
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |