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?
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 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
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.