Book Free Trial

Curriculum

Arithmetic Operations

Subject: ProgrammingCourse: Coding In Python

Theory

Basic Arithmetic Operations
  • A + B — addition
  • A - B — subtraction
  • A * B — multiplication
  • A / B — division (always returns a float)
  • A ** B — exponentiation (e.g. square root: x ** 0.5; nth root: x ** (1/n))

There is also a unary minus operator that takes a single argument and returns its negation:

>> -A
Operator Precedence

When several operations appear in one expression, Python applies them in this order:

  1. Exponentiation, evaluated right to left (so 3 ** 3 ** 3 is 3 ** (3 ** 3)).
  2. Unary minus (negation).
  3. Multiplication and division (including *, /, //, %), evaluated left to right.
  4. Addition and subtraction, evaluated left to right.

For example:

>> 1 + 2 * 3 ** 1 + 18
Integer Division and Modulo

The / operator always produces a float. To perform integer (floor) division—discarding any fractional part—use //:

>> 17 // 3
5
>>> -17 // 3
-6

To get the remainder of a division, use the modulo operator %:

>> 17 % 3
2
>>> -17 % 3
1