A use-case for for...else with no break

Terry Reedy tjreedy at udel.edu
Thu Nov 2 18:20:26 EDT 2017


On 11/2/2017 6:10 AM, Steve D'Aprano wrote:
> 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>

This seems like a bug in how Python interacts with your console. On 
Windows, in Python started from an icon or in Command Prompt:
 >>> for c in 'abc': print(c, end='')
...
abc>>>
IDLE adds \n if needed, so prompts always starts on a fresh line.
 >>> for x in 'abcdefgh':
	print(x, end='')
abcdefgh
 >>>
> "For ... else" to the rescue!
>> py> for char in "abcdefgh":
> ... print(char, end='')
> ... else:
> ... print()
> ...
> abcdefgh
> py>

-- 
Terry Jan Reedy


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /