Why is this code
for i in range(10):
if i == 5: print i
valid while the compound statement (I know that PEP 8 discourages such coding style)
for i in range(10): if i == 5: print i
is not?
Why is this code
for i in range(10):
if i == 5: print i
valid while the compound statement (I know that PEP 8 discourages such coding style)
for i in range(10): if i == 5: print i
is not?
This is because python has strict rules about indentation being used to represent blocks of code and by putting an for
followed by an if
, you create ambiguous indentation interpretations and thus python does not allow it.
For python, you can put as many lines as you want after a if
statement:
if 1==1: print 'Y'; print 'E'; print 'S'; print '!';
as long as they all have the same indentation level, i.e., no if
, while
, for
as they introduce a deeper indentation level.
Hope that helps
The reason why you cannot is because the language simply doesn't support it:
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
It has been suggested many times on the Python mailing lists, but has never really gained traction because it's already possible to do using existing mechanisms...
Such as a filtered generator expression:
for i in (i for i in range(10) if i == 5):
...
The advantage of this over the list comprehension is that it doesn't generate the entire list before iterating over it.
using list comprehension:
In [10]: [x for x in range(10) if x ==5][0]
Out[10]: 5