Python's Curious Behavior with Leading Zeros
When working with Python, you may encounter unexpected results while inputting small integers that begin with 0. This anomaly stems from the language's ability to interpret these numbers in base 8, known as octal numbers.
Specifically, the Python interpreter treats these leading zeros as an indication of an octal representation. For instance, the integer 011 is interpreted as:
011 = 1⋅8¹ + 1⋅8⁰ = 9 (in octal)
This explains why the value 9 is returned when you type "011" into the Python interpreter.
However, this behavior is version-specific. In Python 3, you must explicitly denote an octal constant by using the "0o" prefix. For example:
0o11 = 1⋅8¹ + 1⋅8⁰ = 9 (in octal)
In Python 2.6 and later versions, both the old (leading 0) and new (0o prefix) formats are supported.
To summarize, leading zeros in Python indicate octal numbers. In Python 2, these numbers can be represented using only the leading zeros, while in Python 3, the "0o" prefix is required.
The above is the detailed content of Why Does Python Interpret Numbers with Leading Zeros as Octal?. For more information, please follow other related articles on the PHP Chinese website!