Home > Backend Development > Python Tutorial > Why Does Python Interpret Numbers with Leading Zeros as Octal?

Why Does Python Interpret Numbers with Leading Zeros as Octal?

Mary-Kate Olsen
Release: 2024-11-21 03:34:26
Original
340 people have browsed it

Why Does Python Interpret Numbers with Leading Zeros as Octal?

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)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template