Why a number like 01
gives a Syntax error when 01
is typed in python interactive mode and pressed enter?
When 00
is entered the interpreter evaluates to 0
, however numbers like 01
, 001
or anything which starts with a 0
is entered Syntax error:invalid token is displayed.
Entering 1,000
in prompt evaluates to a tuple of (1,0)
but 1,001
doesn't evaluate to (1,1)
instead Syntax error is displayed.
Why does the Python interpreter behave so?
Historically, integer literals starting with zero denoted octal numbers. This has been abolished in Python 3, and replaced with a different syntax (0o...
).
The old syntax is no longer accepted, except when the number consists entirely of zeros:
Python 3.3.0 (default, Dec 1 2012, 19:05:43)
>>> 0
0
>>> 00
0
>>> 01
File "<stdin>", line 1
01
^
SyntaxError: invalid token
In Python 2.x, a leading zero in an integer literal means it is interpreted as octal. This was dropped for Python 3, which requires the 0o
prefix. A leading zero in a literal was left as a syntax error so that old code relying on the old behavior breaks loudly instead of silently giving the "wrong" answer.
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