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

Steve D'Aprano steve+python at pearwood.info
Thu Nov 2 20:53:01 EDT 2017


On Fri, 3 Nov 2017 09:20 am, Terry Reedy wrote:

> 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>>>

That's still unfortunate: the prompt is immediately after the output, rather
than starting on a new line.


> IDLE adds \n if needed, so prompts always starts on a fresh line.
> 
>  >>> for x in 'abcdefgh':
> print(x, end='')
> 
> abcdefgh
>  >>>

The prompts and the output aren't aligned -- the prompts are indented by an
additional space. Is that intentional?

Does IDLE do this only when writing to an actual console? Because if it does
so even when output is redirected to a file, adding an extra, unexpected
newline would be a bug in IDLE.

In any case, in the interactive interpreter there are times one wishes to
follow a loop with additional code that executes immediately after the loop,
and have them do so *together* without a prompt in between. It might not even
be because you care about the output: you might be timing something, and
don't want it to pause and wait for you to type the following code.

But you cannot write this:


py> for x in seq:
...     do_this()
... do_that()


as the interpreter in interactive mode requires a blank line to terminate the
indented block. But if you include such a blank:


py> for x in seq:
...     do_this()
...
py> do_that()


the output of "do_this()" is separated from the output of "do_that()", which
may be inconvenient.

Another work around is:

if True:
    for x in seq:
        do_this()
    do_that()



-- 
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