Why is a number like 01 giving a syntax error in python interactive mode

Why does a number like 01 give a syntax error when 01 is entered in python interactive mode and enter is pressed?

When you enter 00 interpreter evaluates to 0 , but numbers are entered, such as 01 , 001 or anything starting with 0 . Syntax error: invalid token displayed.

Entering 1,000 at the prompt evaluates the tuple (1,0) , but 1,001 does not evaluate the value (1,1) , but a syntax error appears.

Why does the Python interpreter behave like this?

+4
source share
2 answers

Historically, whole literals starting from zero denote octal numbers. This one was canceled in Python 3 and replaced with a different syntax ( 0o... ).

The old syntax is no longer accepted unless the whole number consists 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 
+10
source

In Python 2.x, a leading zero in an integer literal means that it is interpreted as octal. This was dropped for Python 3, which requires the 0o prefix. The leading zero in the literal remained as a syntax error, so that the old code, relying on the old behavior, breaks loudly, instead of silently giving a "wrong" answer.

+2
source

All Articles