Arithmetic Operators

**

A ** (double asterisk) sign is an exponentiation (power) operator. Its left argument is the base, its right, the exponent.

Remember: It's possible to formulate the following rules based on this result:

when both ** arguments are integers, the result is an integer, too; when at least one ** argument is a float, the result is a float, too.

*

An * (asterisk) sign is a multiplication operator.

/

A / (slash) sign is a divisional operator.

//

A // (double slash) sign is an integer divisional operator. It differs from the standard / operator in two details:

its result lacks the fractional part - it's absent (for integers), or is always equal to zero (for floats); this means that the results are always rounded; it conforms to the integer vs. float rule.

% (modulus)

The next operator is quite a peculiar one, because it has no equivalent among traditional arithmetic operators.

Its graphical representation in Python is the % (percent) sign, which may look a bit confusing.

The remainder of the number

print(14 % 4) == 2

14 - 12 = remainder 2

Operators: how not to divide

As you probably know, division by zero doesn't work.

Do not try to:

  • perform a division by zero;

  • perform an integer division by zero;

  • find a remainder of a division by zero.

Operators and their bindings

The binding of the operator determines the order of computations performed by some operators with equal priority, put side by side in one expression.

Most of Python's operators have left-sided binding, which means that the calculation of the expression is conducted from left to right.

This simple example will show you how it works. Take a look:

print(9 % 6 % 2)

There are two possible ways of evaluating this expression:

from left to right: first 9 % 6 gives 3, and then 3 % 2 gives 1; from right to left: first 6 % 2 gives 0, and then 9 % 0 causes a fatal error.

Operators and their bindings: exponentiation

Repeat the experiment, but now with exponentiation.

Use this snippet of code:

print(2 ** 2 ** 3)

The two possible results are:

2 ** 2 → 4; 4 ** 3 → 64 2 ** 3 → 8; 2 ** 8 → 256

Run the code. What do you see?

The result clearly shows that the exponentiation operator uses right-sided binding.

Solving simple math problems

c = √ a2 + b2 = (a ** 2 + b ** 2) * 0.5

Last updated