Why does entering the expression 011 evaluate to 9?
and 0111 = 73, 01111 = 585, and so on.

Dani AI

Generated

As noticed and confirmed, the behavior comes from how integer literals were written in older Python: a leading zero in a source literal indicates octal. That is a parsing-time rule in the language, not an arithmetic quirk. See the language reference for details in the version you care about: Python 2 integer literal rules and the updated rules in Python 3.

In modern Python (3.x) the old leading-zero octal syntax was removed; octal literals must use the 0o prefix. Practical examples to use today:

0o11          # octal literal (Python 3) -> decimal 9

int('11', 8)  # parse the string '11' as base 8 -> 9
int('011', 10) # force decimal parsing of a string with leading zero -> 11

Migration tips and cautions: legacy code written for Python 2 that contains things like 0644 (file modes, constants) will raise SyntaxError under Python 3; update them to 0o644 or use explicit parsing. Use automated tools (for example, 2to3) or search for the regex pattern \b0[0-7]+ to locate candidate literals. Remember that int() parsing of strings is separate from source literals — use int(s, base) to control interpretation. For authoritative behavior, consult the linked language-reference pages for your Python version.

Recommended Answers

All 2 Replies

It must be notation for base 8.

You figured it out!

print 011  # --> 9  (the denary for octal 011)
 
print 0xff  # --> 255 (the denary of hex ff)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.