A use-case for for...else with no break
Steve D'Aprano
steve+python at pearwood.info
Thu Nov 2 06:10:39 EDT 2017
Occasionally it is useful to loop over a bunch of stuff in the interactive
interpreter, printing them as you go on a single line:
for x in something():
print(x, end='')
If you do that, the prompt overwrites your output, and you get a mess:
py> for x in "abcdefgh":
... print(x, end='')
...
py> efghpy>
"For ... else" to the rescue!
py> for char in "abcdefgh":
... print(char, end='')
... else:
... print()
...
abcdefgh
py>
--
Steve
“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