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

Erik python at lucidity.plus.com
Mon Oct 3 18:18:36 EDT 2016


Hi,

On 11/09/16 10:36, Dominik Gresch wrote:
> So I asked myself if a syntax as follows would be possible:
>
> for i in range(10) if i != 5:
>     body

I've read the thread and I understand the general issues with making the 
condition part of the expression.

However, what if this wasn't part of changing the expression syntax but 
changing the declarative syntax instead to remove the need for a newline 
and indent after the colon? I'm fairly sure this will have been 
suggested and shot down in the past, but I couldn't find any obvious 
references so I'll say it (again?).

The expression suggested could be spelled:

for i in range(10): if i != 5:
     body

So, if a colon followed by another suite is equivalent to the same 
construct but without the INDENT (and then the corresponding DEDENT 
unwinds up to the point of the first keyword) then we get something 
that's pretty much as succinct as Dominik suggested.

Of course, we then might get:

for i in myweirdobject: if i != 5: while foobar(i) > 10: while frob(i+1) 
< 99:
     body

... which is hideous. But is it actually _likely_?

E.


More information about the Python-ideas mailing list