2

Why does Python behave strangely when I store integers with leading zeros into a variable? One gives an error while the other one stores the value wrongly?

>>> zipcode = 02492
SyntaxError: invalid token

>>> zipcode = 02132
>>> zipcode
1114
Nyxynyx
  • 61,411
  • 155
  • 482
  • 830

2 Answers2

6

Numbers beginning with a 0 are interpreted as octal numbers.

In [32]: oct(1114)
Out[32]: '02132'

In [33]: int('2132', 8)
Out[33]: 1114

In [34]: 02132 == 1114
Out[34]: True

Note that in Python3, octal literals must be specified with a leading 0o or 0O, instead of 0.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
3

int literals with leading zero are interpreted as octal, in which 9 is not a valid number. Only numbers formed with digits in range [0, 7] are valid octal numbers.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525