-
Notifications
You must be signed in to change notification settings - Fork 0
Chapter 2 (Operations)
Coding requires math, and that calls for some arithmetic operators.
| Operator | Function | Example |
|---|---|---|
+ |
Addition |
>>> 1 + 12
|
- |
Subtraction |
>>> 2 - 3-1
|
* |
Multiplication |
>>> 5 * 735
|
/ |
Division |
>>> 9 / 61.5
|
// |
Floor division |
>>> 9 // 61
|
% |
Modulus |
>>> 9 % 63
|
** |
Exponentiation |
>>> 5 ** 225
|
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?
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/PEMDAS represents the order of mathematical operations, which is exactly the same as in math.
In descending order of priority, we have:
- B/P: Brackets/Parentheses (
()) - O/E: Orders/Exponents (
**) - D & M: Division & Multiplication (
/,//,%,*) - 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
-1Simple 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.
By a team of students from NUS High School, aiming to make coding easier for everyone.