Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a number like 01 gives a Syntax error in python interactive mode [duplicate]

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?

like image 664
Pradeesh Avatar asked Apr 12 '13 08:04

Pradeesh


2 Answers

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
like image 182
NPE Avatar answered Oct 04 '22 12:10

NPE


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.

like image 24
lvc Avatar answered Oct 04 '22 12:10

lvc