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, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access