So I saw these two questions on twitter. How is 1.real
a syntax error but 1 .real
is not?
>>> 1.real File "<stdin>", line 1 1.real ^ SyntaxError: invalid syntax >>> 1 .real 1 >>> 1. real File "<stdin>", line 1 1. real ^ SyntaxError: invalid syntax >>> 1 . real 1 >>> 1..real 1.0 >>> 1 ..real File "<stdin>", line 1 1 ..real ^ SyntaxError: invalid syntax >>> 1.. real 1.0 >>> 1 .. real File "<stdin>", line 1 1 .. real ^ SyntaxError: invalid syntax
Syntax errors are produced by Python when it is translating the source code into byte code. They usually indicate that there is something wrong with the syntax of the program. Example: Omitting the colon at the end of a def statement yields the somewhat redundant message SyntaxError: invalid syntax.
I guess that the .
is greedily parsed as part of a number, if possible, making it the float
1.
, instead of being part of the method call.
Spaces are not allowed around the decimal point, but you can have spaces before and after the .
in a method call. If the number is followed by a space, the parse of the number is terminated, so it's unambiguous.
Let's look at the different cases and how they are parsed:
>>> 1.real # parsed as (1.)real -> missing '.' >>> 1 .real # parsed as (1).real -> okay >>> 1. real # parsed as (1.)real -> missing '.' >>> 1 . real # parsed as (1).real -> okay >>> 1..real # parsed as (1.).real -> okay >>> 1 ..real # parsed as (1)..real -> one '.' too much >>> 1.. real # parsed as (1.).real -> okay >>> 1 .. real # parsed as (1)..real -> one '.' too much
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