[Tutor] Octal confusion, please explain why. Python 3.2
Steven D'Aprano
steve at pearwood.info
Sat Jun 2 13:51:59 CEST 2012
Jordan wrote:
> Hello, first off I am using Python 3.2 on Linux Mint 12 64-bit.
> I am confused as to why I can not successfully compare a variable that
> was created as an octal to a variable that is converted to an octal in a
> if statement yet print yields that they are the same octal value.
Because the oct() function returns a string, not a number.
py> oct(63)
'0o77'
In Python, strings are never equal to numbers:
py> 42 == '42'
False
Octal literals are just regular integers that you type differently:
py> 0o77
63
"Octals" aren't a different type or object; the difference between the numbers
0o77 and 63 is cosmetic only. 0o77 is just the base 8 version of the base 10
number 63 or the binary number 0b111111.
Because octal notation is only used for input, there's no need to covert
numbers to octal strings to compare them:
py> 0o77 == 63 # no different to "63 == 63"
True
The same applies for hex and bin syntax too:
py> 0x1ff == 511
True
--
Steven
More information about the Tutor
mailing list