-1

In my python script, I do the following:

>>> x = 0123456

However, when I print this, it comes out as this:

>>> x = 0123456
>>> print x
42798

Does this have to do with the zero in front? Or is it just my computer?

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
  • Numbers starting with 0 are interpreted as octal. – devnull Feb 23 '14 at 04:20
  • 1
    Some of the sub-questions can be trivially self-answered: 1) To see if "it has to do with zero in front:" `x = 123456`; 2) To "verify it's not your computer" (http://ideone.com) – user2864740 Feb 23 '14 at 04:24

2 Answers2

2

A number literal starts with 0 is considered as an octal number. You can realize it like this

print int("123456", 8)   # 42798

Here we asked int function to consider the number 123456 as a base 8 number.

Note that this will work only in Python 2.7. Because in Python 2.7, octal numbers are defined like this

octinteger     ::=  "0" ("o" | "O") octdigit+ | "0" octdigit+

But in Python 3.x, this is changed to

octinteger     ::=  "0" ("o" | "O") octdigit+

So, In Python 3.x this will be treated as Syntax error,

x = 0123456
# SyntaxError: invalid token

If at all you are going to represent octal numbers in your code, you should do

x = 0o123456    # Remember the o (for octal) after the first 0

This will work in both Python 2.7 and 3.x

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1

leading 0 means it's being interpreted as an octal number. Octal 0123456 is 42798 decimal. Similarly, if you had x = 0x123456, you'd be printing out 1193046, because 0x means it's a hexadecimal number.

Marc B
  • 356,200
  • 43
  • 426
  • 500