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?

3
  • 3
    Did you try 08 or 09? (just checking the quality of your scientific method) Commented Aug 8, 2010 at 5:11
  • See [ Python: Invalid Token ](stackoverflow.com/questions/336181/python-invalid-token). Commented Aug 8, 2010 at 5:16
  • Please Read the Language Manual first. docs.python.org/reference/…. This is already well documented, and you could save yourself some time by reading the manual instead of experimenting randomly. Commented Aug 8, 2010 at 13:18

3 Answers 3

13

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

007 == 7
010 == 8
011 == 9
Sign up to request clarification or add additional context in comments.

1 Comment

-1: Forgot the all-import RTFM link: docs.python.org/reference/….
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.

Comments

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))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.