views:

148

answers:

4

When using the interactive shell:

print 010

I get back an 8.

I started playing around using other numbers having zeroes before (0110 = 72, 013 = 11) but I could not figure it out...

What is going on here?

+3  A: 

like many languages, an integer with a leading zero is interpreted as an octal. this means that it's base eight. for example, 020 has decimal value 16 and 030 has decimal value 24. for the sake of completeness, this is how it works. value takes a string and returns the decimal value of that string interpreted as an octal. It doesn't do any error checking so you have to make sure that each digit is between 0 and 8. no leading 0 is necessary.

    def value(s):
        digits = [int(c) for c in s]
        digits.reverse()
        return sum(d * 8**k for k, d in enumerate(digits))
aaronasterling
+10  A: 

Numbers entered with a leading zero are interpreted as octal (base 8).

007 == 7
010 == 8
011 == 9
MikeyB
-1: Forgot the all-import RTFM link: http://docs.python.org/reference/lexical_analysis.html#integer-and-long-integer-literals.
S.Lott
+3  A: 

Python adopted C's notation for octal and hexadecimal literals: Integer literals starting with 0 are octal, and those starting with 0x are hex.

The 0 prefix was considered error-prone, so Python 3.0 changed the octal prefix to 0o.

dan04