Skip to content

Chapter 2 (Operations)

VikramRamanathan edited this page Jan 19, 2022 · 1 revision

Some Math

Coding requires math, and that calls for some arithmetic operators.

Operator Function Example
+ Addition >>> 1 + 1
2
- Subtraction >>> 2 - 3
-1
* Multiplication >>> 5 * 7
35
/ Division >>> 9 / 6
1.5
// Floor division >>> 9 // 6
1
% Modulus >>> 9 % 6
3
** Exponentiation >>> 5 ** 2
25

Remember never to use ^ for exponents! It is a bitwise operator with a totally different function. It may not always throw an error, which means that you may unknowingly end up with a wrong output!

Seems simple enough? Yes!

But wait... what is floor division and modulus?

Division, but not quite

9 ÷ 6 = 1 R 3
Floor division: 9 // 6 = 1
Modulus: 9 % 6 = 3 (This is read as 9 modulo/mod 6 equals 3.)

Nowww it makes sense. Floor division returns the quotient, while modulus returns the remainder.

But what happens if you have multiple operations in one line?

BODMAS, or PEMDAS

BODMAS/PEMDAS represents the order of mathematical operations, which is exactly the same as in math.

In descending order of priority, we have:

  1. B/P: Brackets/Parentheses (())
  2. O/E: Orders/Exponents (**)
  3. D & M: Division & Multiplication (/, //, %, *)
  4. A & S: Addition & Subtraction (+, -)

All of this is the same as in math!

For example...

>>> 3 * 5 ** 2
75
>>> (3 * 5) ** 2
225
>>> 3 + 4 - 2 ** 3
-1

Simple enough? Try out some trickier exercises, and check your answers by typing them out in IDLE.

>>> 25 // 6 - 4 // 2 * 3 / 2

>>> 123 // 4 ** 2 - 3 / 2 ** (4 * 7 - 30)

And that's it! Remember your arithmetic operators and their orders, and you're set for most of the math that you will encounter when coding with Python.

Clone this wiki locally