"for/while ... break(by any means) ... else" make sense?
Steven D'Aprano
steve at pearwood.info
Tue Jun 28 22:43:39 EDT 2016
On Wed, 29 Jun 2016 11:41 am, jfong at ms4.hinet.net wrote:
> Anyone who wrote the code below must be insane:-)
>
> for x in range(3):
> print(x)
> else:
> print('I am done')
*shrug* Insane or not, it's legal.
import math
pass
import os
pass
import sys
is "insane" too, but still legal. The Python interpreter does not judge your
code.
> But here it seems perfectly OK:
>
> for x in range(3):
> print(x)
> if x == 1: break
> else:
> print('I am done')
>
> To me, the "else" was bonded with "break" (or return, or raise, or...),
> not "for". It make sense:-)
Just ten minutes ago I wrote code that looks like this:
for x in sequence:
try:
do_something(x)
except Error:
continue # try again with the next item
break
else:
default()
The "else" in for...else has nothing to do with any "if" inside the for
block.
--
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list