Numbers Starting with 0 in Python: Unmasking the Mystery
In Python, when you encounter numbers with a leading zero, they may seem puzzling. These numbers represent values in octal, or base-8 notation.
Octal Notation
In octal notation, numbers are expressed using only the digits 0 to 7. The leading zero indicates that the number is in octal format.
Conversion from Octal to Decimal
To convert an octal number to decimal, multiply each digit by the corresponding power of 8, starting from the rightmost digit. Sum the results to obtain the decimal value.
Examples
In Python 2.7.3, the following conversions apply:
Handling Octal Numbers in Python
In Python 3.0 and above, octal numbers must be prefixed with "0o". For example:
Python 2.6 and above supports both the old format (without prefix) and the new format (with "0o" prefix).
Conclusion
Numbers starting with 0 in Python represent values in octal notation. By understanding the principles of octal conversion, you can correctly interpret and work with these seemingly peculiar numbers.
The above is the detailed content of What Do Numbers Starting with 0 Mean in Python?. For more information, please follow other related articles on the PHP Chinese website!