I can join lines in Python using semi-colon, e.g.
a=5; b=10
But why can't I do the same with for
x=['a','b']; for i,j in enumerate(x): print(i,":", j)
Because the Python grammar disallows it. See the documentation:
stmt_list ::= simple_stmt (";" simple_stmt)* [";"]
Semicolons can only be used to separate simple statements (not compound statements like for
). And, really, there's almost no reason to ever use them even for that. Just use separate lines. Python isn't designed to make it convenient to jam lots of code onto one line.
The short (yet valid) answer is simply "because the language grammar isn't defined to allow it". As for why that's the case, it's hard if not impossible to be sure unless you ask whoever came up with that portion of the grammar, but I imagine it's due to readability, which is one of the goals of Python1.
Why would you ever want to write something obscure like that? Just split it up into multiple lines:
x = ['a','b']
for i,j in enumerate(x):
print(i, ":", j)
I would argue that this variant is much clearer.
1 From import this
: Readability counts.
Because Guido van Rossum, the creator of Python, and other developers, don't actually like the "semicolons and braces" style of code formatting.
For a brief look at how they feel about these things, try:
from __future__ import braces
Statements in Python are supposed to be separated by blank lines, and compound statements in Python are supposed to be bounded by indentation.
The existence of ;
and one-line compound statements (e.g. for i in x: print i
) are meant to be only very limited concessions... and you can't combine them.
The grammar of Python does not allow this. It's a good answer, but what's the reason for it?
I think the logic behind the decision is the following: body of a for loop must be indented in order to be recognized. So, if we allow not a simple_stmt
there, it would require a complex and easy-to-break indentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With