# Numeric Operations

Python supplies the usual numeric operations, as you’ve just seen in Table 4-2. All numbers are immutable objects, so when you perform a numeric operation on a number object, you always produce a new number object. You can access the parts of a complex object `z` as read-only attributes `z.real` and `z.imag`. Trying to rebind these attributes on a complex object raises an exception.

Note that a number’s optional `+` or `-` sign, and the `+` that joins a floating-point literal to an imaginary one to make a complex number, are not part of the literals’ syntax. They are ordinary operators, subject to normal operator precedence rules (see Table 4-2). This is why, for example, `-2**2` evaluates to `-4`: exponentiation has higher precedence than unary minus, so the whole expression parses as `-(2**2)`, not as `(-2)**2`.

## Coercion and Conversions

You can perform arithmetic operations and comparisons between any two numbers. If the operands’ types differ, `coercion` applies: Python converts the operand with the smaller type to the larger type. The types, in order from smallest to largest, are integers, long integers, floating-point numbers, and complex numbers.

You can also perform an explicit conversion by passing a numeric argument to any of the built-ins: `int`, `long`, `float`, and `complex`. `int` and `long` drop their argument’s fractional part, if any (e.g., `int(9.8)` is `9`). Converting from a complex number to any other numeric type drops the imaginary part. You can also call `complex` with two arguments, giving real and imaginary parts.

Each built-in type can also take a string argument with the syntax of an appropriate numeric literal with two small extensions: the argument string may start with a sign and, for complex numbers, may sum or subtract real and imaginary parts. `int` and `long` can also be called with two arguments: the first one a string to convert, and the second one the radix, an integer between 2 and 36 to use as the base for the conversion (e.g., `int('101',2)` returns `5`, the value of '`101`' in base `2`).

## Arithmetic Operations

If the right operand of `/`, `//`, or `%` is `0`, Python raises a runtime exception. The `//` operator, introduced in Python 2.2, performs truncating division, which means it returns an integer result (converted to the same type as the wider operand) and ignores the remainder, if any. When both operands are integers, the `/` operator behaves like `//` if you are using Python 2.1 and earlier or if the switch `-Qold` was used on the Python command line (`-Qold` is the default in Python 2.2). Otherwise, `/` performs true division, returning a floating-point result (or a complex result, if either operand is a complex number). To have `/` perform true division on integer operands in Python 2.2, use the switch `-Qnew` on the Python command line or begin your source file with the statement:

`from __future__ import division`

This ensures that operator `/` works without truncation on any type of operands.

To ensure that your program’s behavior does not depend on the `-Q` switch, use `//` (in Python 2.2 and later) to get truncating division. When you do not want truncation, ensure that at least one operand is not an integer. For example, instead of `a/b`, use `1.*a/b` to avoid making any assumption on the types of `a` and `b`. To check whether your program has version dependencies in its use of division, use the switch `-Qwarn` on the Python command line (in Python 2.2 and later) to get warnings about uses of `/` on integer operands.

The built-in `divmod` function takes two numeric arguments and returns a pair whose items are the quotient and remainder, thus saving you from having to use both `//` for the quotient and `%` for the remainder.

An exponentiation operation, `a` `**` `b`, raises an exception if `a` is less than zero and `b` is a floating-point value with a non-zero fractional part. The built-in `pow(` `a`,`b` `)` function returns the same result as `a` `**` `b`. With three arguments, `pow(` `a`,`b`,`c` `)` returns the same result as `(` `a` `**` `b` `)%` `c`, but faster.

## Comparisons

All objects, including numbers, can also be compared for equality (`= =`) and inequality (`!=`). Comparisons requiring order (`<`, `<=`, `>`, `>=`) may be used between any two numbers except complex ones, for which they raise runtime exceptions. All these operators return Boolean values (`True` or `False`).

## Bitwise Operations on Integers

Integers and long integers can be considered strings of bits and used with the bitwise operations shown in Table 4-2. Bitwise operators have lower priority than arithmetic operators. Positive integers are extended by an infinite string of `0` bits on the left. Negative integers are represented in two’s complement notation, and therefore are extended by an infinite string of `1` bits on the left.

Get Python in a Nutshell now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.