Python Math Operators
Operator | Name | Notes |
+ | add | |
– | subtract | |
* | multiply | |
/ | divide | 7 / 2 = 3.5 (can return a float) |
// | divide , floor | 7 // 2 = 3 (always returns int) |
% | modulus | 11 % 3 = 2 (remainder of 11 / 3) |
** | exponent | 3 ** 4 = 81 |
Division Notes:
Sometimes you want a float (decimal) result. In that case, use a single slash:
print(7/3) 2.3333333333333335
(read this if you want an explanation for that 5 at the end)
In other cases, you need an int (integer) result. Use the double slash operator, and it will take the floor of the division result, which means that it rounds down to the nearest integer:
print(7//3) 2
Modulus Operator (%)
(also known as “modulo” or “mod”)
The modulus operator gives you the remainder of a division operation.
Operation | Expression | Result |
Division with Remainder | 19 ÷ 5 | 3 R 4 |
Modulus | 19 % 5 | 4 |
Uses of modulus operator:
Check if a number is even: even numbers have a remainder of zero when divided by 2. (remainder equals one for odd numbers)
# We will learn if/else very soon. if x%2 == 0: # commands to do if x is even else: # commands to do if x is odd
“Wrap around” Addition:
Sometimes we want to limit our answer to a range of numbers.
Example: if today is Tuesday, what day of the week will it be 137 days from now? In this case, we want to divide this by 7, but we only want an answer in the range of 0 through 6 so we can turn that number into a day of the week.
Solution:
Treat the days of the week as numbers from 0 to 6; [0,1,2,3,4,5,6]
Tuesday is day 2.
In 137 days, it will be day 139 since 2 + 137 = 139.
Since there are only 7 days in the week,
take the modulo of 139 with a divisor of 7.
139 % 7 = 6
Day 6 is Saturday.
# this example uses a list, which we learn later. days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'] d = 139 % 7 print(d) print(days[d]) OUTPUT: 6 Sat
Do something every “nth” time (n is any positive integer). The following program has a loop that prints “BOO” every 7th time:
for i in range(100): print(i) if i%7 == 0: print("BOO")
Built In Math Functions
(available without importing anything)
min(), max()
Minimum or maximum value from a list of arguments or a collection
# multiple arguments separated by comma lowest = min(74, 10, 102) # single collection argument numbers = [5.3, -7.8, 4.9, 1.23] max(numbers) # sum of x and y, up to a maximum of 255 min(x + y, 255) # difference of A and B, with minimum result of 0 max(A - B, 0)
abs()
Absolute Value
abs(-7) RESULT: 7
round()
Round to nearest integer or to a number of decimal places
# Round to nearest integer round(235.627) RESULT: 236 # Round to nearest 0.01 round(312.2387523, 2) RESULT: 312.24 # Round to nearest 1000 round(23156.78, -3) RESULT: 23000.0
To round down, you can use int() function (converts to integer):
int(6.89) RESULT: 6
sum()
Sums the numbers in a collection (e.g. list)
# sum two numbers sum(3, 5) RESULT: 8 # sum a list variable values = [2, 7, 3, 1, 5] sum(values) RESULT: 18 # wrong way to use sum: sum(2, 7, 3, 1, 5) TypeError: sum expected at most 2 arguments, got 5 # fixed using [square brackets] to get to 1 argument sum([2, 7, 3, 1, 5]) OUTPUT: 18
pow()
Exponentiation, including modular exponentiation
(fast modular exponentiation is important in cryptography; pow() is able to perform modular exponentiation for large numbers)
# regular exponentiation: x^y # same as 5 ** 3 pow(5, 3) OUTPUT: 125 # modular exponentiation: (x^y)%z # same as (1234 ** 5678) % 52 pow(1234, 5678, 52) OUTPUT: 40
More Math Functions – import math
You can import math to access many other math functions.
docs.python.org/3/library/math.html
import math print(math.sin(math.pi/6)) print(math.exp(1)) print(math.log(2)) print(math.log(1000, 10)) print(math.sqrt(49))
Math Operators Examples:
x = 3 + 5 print(x - 12) z = 4 * (2.5 + x)
Python follows typical order of operations:
1) Expressions inside parentheses
2) Exponents
3) Multiplication and division
4) Addition and subtraction
Code can have multiple levels of nested parentheses from functions and math expressions.
They are evaluated in an “inside-out” order and using the order of operations rules above.
Each time a function is evaluated, it is replaced with its return value (i.e. output) in the expression.
Example:
x = 7 y = 4 r = round(x**y*(abs(2-x)+3), -1)
Here are the steps Python works through to evaluate this expression. The equation is shown slightly more simplified after each step.
1) Innermost Parentheses: (2-x) = (2-7) = -5:
r = round(x**y*(abs(-5)+3), -1)
2) abs(-5) = 5:
r = round(x**y*(5+3), -1)
3) (5 + 3) = 8:
r = round(x**y*(8), -1)
4) Exponentiation is before multiplication: x**y = 7**4 = 2401:
r = round(2401*(8), -1)
5) The parentheses around the 8 are now irrelevant:
r = round(2401*8, -1)
6) 2401*8 = 19208:
r = round(19208, -1)
7) Round to -1 digits (nearest 10):
r = 19210
If expressions like this are confusing, here are two pieces of advice:
1) Practice thinking through multi-part expressions!
2) Write expressions out as multiple steps instead of putting them all into one line of code.
Here’s a comparison for the example expression from above:
One line of code:
r = round(x**y*(abs(2-x)+3), -1)
Same math split into multiple lines of code:
B = abs(2-x) + 3 C = x**y*B D = round(C, -1) print(D)
If you find it easier to see what’s happening when the operations are split into separate lines of code, it’s fine to do it that way.