2

Possible Duplicate:
How do you express binary literals in Python?

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?

Community
  • 1
  • 1
AlexBrand
  • 11,971
  • 20
  • 87
  • 132
  • 3
    Did you try 08 or 09? (just checking the quality of your scientific method) – Kobi Aug 08 '10 at 05:11
  • See [ Python: Invalid Token ](http://stackoverflow.com/questions/336181/python-invalid-token). – Matthew Flaschen Aug 08 '10 at 05:16
  • Please Read the Language Manual first. http://docs.python.org/reference/lexical_analysis.html#integer-and-long-integer-literals. This is already well documented, and you could save yourself some time by reading the manual instead of experimenting randomly. – S.Lott Aug 08 '10 at 13:18

3 Answers3

13

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

007 == 7
010 == 8
011 == 9
MikeyB
  • 3,288
  • 1
  • 27
  • 38
  • -1: Forgot the all-import RTFM link: http://docs.python.org/reference/lexical_analysis.html#integer-and-long-integer-literals. – S.Lott Aug 08 '10 at 13:17
3

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
  • 68,820
  • 20
  • 127
  • 125
3

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
  • 87,747
  • 23
  • 163
  • 198