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

Why Does Python 2.x Interpret Numbers with Leading Zeros as Octal?

Patricia Arquette
Release: 2024-11-26 12:08:09
Original
613 people have browsed it

Why Does Python 2.x Interpret Numbers with Leading Zeros as Octal?

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

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:

  • 011 represents 1 x 8¹ 1 x 8⁰ = 9
  • 0100 represents 1 x 8² 0 x 8¹ 0 x 8⁰ = 64
  • 027 represents 2 x 8¹ 7 x 8⁰ = 16 7 = 23

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

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!

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