Math in Python

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

Division in Python 2 and Python 3: the single slash operator does regular division in Python 3, but it does floor division in Python 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: they have a remainder of zero when divided by 2. (remainder equals one for odd numbers)

if x%2 == 0:
    #do stuff if even

“Wrap around” Addition:

Example: if today is Tuesday, what day of the week will it be 137 days from now?

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

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

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)

OUTPUT: 7

round()
Round to nearest integer or to a number of decimal places

# Round to nearest integer
round(235.627)
OUTPUT: 236

# Round to nearest 0.01
round(312.2387523, 2)
OUTPUT: 312.24

# Round to nearest 1000
round(23156.78, -3)
OUTPUT: 23000.0

sum()
Sums the numbers in a collection (e.g. list)

# sum a list variable
values = [2, 7, 3, 1, 5]
sum(values)
OUTPUT: 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

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.