1

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
  • 56,949
  • 141
  • 437
  • 770

2 Answers2

5

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
  • 777,569
  • 165
  • 1,697
  • 1,613
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
  • 203,151
  • 43
  • 392
  • 509