[Python-ideas] if-statement in for-loop

Nick Coghlan ncoghlan at gmail.com
Mon Sep 12 02:25:11 EDT 2016


On 11 September 2016 at 19:36, Dominik Gresch <greschd at gmx.ch> wrote:
> Hi,
>
> I've recently found myself writing code similar to this:
>
> for i in range(10):
>     if i == 5:
>         continue
>     "body"
>
> which I find a bit ugly. Obviously the same could be written as
>
> for i in range(10):
>     if i != 5:
>         "body"
>
> but here you would have to look at the end of the body to see if something
> happens when i==5.
> So I asked myself if a syntax as follows would be possible:
>
> for i in range(10) if i != 5:
>     body
>
> Personally, I find this extremely intuitive since this kind of if-statement
> is already present in list comprehensions.
>
> What is your opinion on this? Sorry if this has been discussed before -- I
> didn't find anything in the archives.

Generally speaking, we only add new syntax in cases where we're
prepared to say "In all cases where the new syntax applies, it should
be used in preference to existing alternative spellings".

Special casing a single "if-continue" in a loop body doesn't meet that
(deliberately high) bar, with Paul Moore's email going into some more
detail on the specifics of that.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list