Decoding the Mysterious "0" Leading Numbers in Python
When you type small integers with a leading zero into Python 2.7.3, they yield unexpected results, such as:
>>> 011 9 >>> 0100 64 >>> 027 23
This quirk stems from the way Python interprets numbers prefixed with "0". In Python 2.x, these numbers are considered octal (base 8) integers.
Unveiling the Octal Numbers
In the octal number system, each digit represents powers of 8. For instance:
Python 3's Modern Approach
Unlike Python 2.7.3, Python 3.0 does not recognize numbers with leading "0" as octal integers and instead raises an error. To represent octal numbers in Python 3, one must use the "0o" prefix, e.g.:
>>> 0o11 9 >>> 0o100 64 >>> 0o27 23
Legacy Support in Python 2.x
Python 2.x versions >= 2.6 support both the old format (leading "0") and the new format (leading "0o") for octal numbers, providing backward compatibility.
The above is the detailed content of Why Does Python 2.x Interpret Numbers with Leading Zeros as Octal?. For more information, please follow other related articles on the PHP Chinese website!