Home > Articles > Open Source > Python

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Integer Updates

Python 3 will feature numerous changes to integer types. One type will be removed, the division operator is changing, and new and modified integer literals are on their way. The following sections discuss all three changes.

Single Integer Type

Python's two different integer types (int and long) began their unification in 2.2. That change is almost complete, with the "new" int behaving like a long. There are no more OverflowError exceptions when you exceed the native integer size, and the trailing L has been dropped. This change is outlined in PEP 237. long still exists in 2.x but is gone in 3.0.

Changes to Division

The current division operator (/) doesn't give the expected answer for those who are new to programming, so it has been changed to do so. If there is any controversy with this change, it's that programmers are used to the floor division functionality. However, try to convince a newbie to programming that one divided by two is zero (1 / 2 == 0). The simplest way to describe this change is with examples. The following examples are excerpted from my article "Keeping Up with Python: the 2.2 Release," published in the July 2002 issue of Linux Journal. You can also find out more about this update in PEP 238.

Classic Division

The default 2.x division operation: Given two integer operands, / performs integer floor division (truncates the fraction as in the preceding example). If at least one float is involved, true division occurs:

>>> 1 / 2   # floor
0
>>> 1.0 / 2.0  # true
0.5

True Division

In Python 3.x, given any two numeric operands, / always returns a float:

>>> 1 / 2   # true
0.5
>>> 1.0 / 2.0  # true
0.5

To try true division starting in Python 2.2, you can either import division from the __future__ module or use the -Qnew switch.

Floor Division

The double-slash division operator (//) was added in 2.2 to perform floor division regardless of operand type and to begin the transition process:

>>> 1 // 2   # floor
0
>>> 1.0 // 2.0  # floor
0.0

Binary and Octal Literals

The minor integer-literal changes were added in Python version 2.6 to make literal non-decimal (hexadecimal, octal, and new binary) formats consistent. Hex representation stays the same with its leading 0x or 0X, whereas the octal formerly led with a single 0. This arrangement proved confusing to some users, so it has been changed to 0o for consistency; for example, instead of 0177, you must use 0o177. Finally, the new binary literal lets you provide the bits of an integer value, prefixed with a leading 0b, as in 0b0110. Python 3.0 doesn't accept 0177. For more information on integer literals updates, see PEP 3127.

  • + Share This
  • 🔖 Save To Your Account