Reputation: 1772
I just started learning pyhton and while working with comparison operators,i got this error when i executed the following code with '==' operator,
40 == 0040.0
resulted into True,from the interpreter,and also
40 == 40.0
resulted in True
but when i executed the below code,
40 == 0040
it throwed an error as,
File "stdin", line 1
40 == 0040
SyntaxError: invalid token
pointing invalid token to trailing zero.
Please help me to understand what is happening.Thank you in advance.
Upvotes: 1
Views: 4224
Reputation: 913
Python 3 doesn't allow numbers with leading zeroes to prevent confusion with octal values. If you must have leading zeroes, use format()
.
It's clearer in Python 2 where 40 == 0040
evaluates to False
.
EDIT: Example taken from link in comment:
>>> "{0:0>3}".format(1)
'001'
Further explanation:
{0 : 0 > 3}
│ │ │ │
│ │ │ └─ Width of 3
│ │ └─ Align Right
│ └─ Fill with '0'
└─ Element index
Upvotes: 1
Reputation:
For floating point numbers, leading zeros are accepted, and them simply ignored (since they don't contribute anything but readability).
Thus, 0040.0
is the floating point number 40.0
.
For integer numbers, the zero at the start of a number takes on a different meaning: depending on the next character, it indicates the rest of the number should be interpreted as an octal (o
or O
), hexadecimal (x
or X
) or binary number (b
or B
).
If another character follows the first 0
, it will be a SyntaxError
. That is what you're seeing for 0040
: there is no hint that it should be a floating point number (no 'e', 'd' or a decimal point, '.'), nor is the second zero a prefix for an different integer base.
The exact definitions for floating point and integer numbers are given in the lexical analysis of the Python reference.
The results of your comparisons evaluating to True
is a different beast, and just indicates that floating point 40 happens to be an exact representation, equal to integer 40.
(For how and why on integers and floats, see for example the SO question that ask about the first integer that can't be represented by a float.)
Upvotes: 1