Why can spaces sometimes be omitted before and after key words? For example, why is the expression 2if-1e1else 1
valid?
Seems to work in both CPython 2.7 and 3.3:
$ python2
Python 2.7.3 (default, Nov 12 2012, 09:50:25)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 2if-1e1else 1
2
$ python3
Python 3.3.0 (default, Nov 12 2012, 10:01:55)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 2if-1e1else 1
2
and even in PyPy:
$ pypy
Python 2.7.2 (341e1e3821ff, Jun 07 2012, 15:42:54)
[PyPy 1.9.0 with GCC 4.2.1] on darwin
Type "help", "copyright", "credits" or "license" for more information.
And now for something completely different: ``PyPy 1.6 released!''
>>>> 2if-1e1else 1
2
Identifiers in python are described as:
identifier ::= (letter|"_") (letter | digit | "_")*
Hence, 2if
can't be an identifier hence if must be 2
,if
. Similar logic applies to the rest of the expression.
Basically interpreting 2if-1e1else 1
would go something like this (the full parsing would be quite complicated):
2if
not valid identifier, 2
matches digit digit ::= "0"..."9"
,if
matches keyword.
-1e1else
, -1
is the unary negation (u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr
) of : ( 1
which matches intpart
in exponentfloat ::= (intpart | pointfloat) | exponent
, e1
is exponent exponent ::= ("e" | "E") ["+" | "-"] digit+
.) You can see expressions of the form Ne+|-x
yields a float this from:
>>> type(2e3)
<type 'float'>
then the else
is seen as the keyword, and -1
etc..
You can peruse the gammar to read more about it.
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