Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

Why is "1.real" a syntax error but "1 .real" valid in Python?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...