Python Math Fundamentals

How strong is your Python Math foundation? Do a quick review of the basics. Then download and try out the 1-page Python Math Quiz!

How strong is your Python Math foundation? Do a quick review of the basics. Then download and try out the 1-page Python Math Quiz!

Python Math

Mathematical Operators

Mathematical operators in Python work in similar ways to how they work in math.

Operator

Description

Example

Addition

a + b = 30

Subtraction

a – b = -1

Multiplication

a * b = 100

Division

b / a = 2.0

*division by zero throws an error

Modulus

b % a = 1


Working with decimals

One thing to note is that when decimal numbers and integers are mixed in a statement, decimal numbers are given as a result.

Example - 1:

a = 1.0

b = 2

print(a - b)


OUTPUT: - 1.0

Example - 2:

a = 1.0

b = 3

print(a * b)


OUTPUT: 3.0


Order of operations

Python follows the order of operations just like math which goes:

parentheses >> multiplication/ division >> addition/ subtraction

Example - 1:

print( 5 + 1 * 2)


OUTPUT: 7

Example - 2:

print( 3 / 2 - 1 * (3 - 1))


OUTPUT: - 0.5


Modulus %

Modulus is super useful in programming. Modulus divides the left-hand operand by the right-hand operand and returns the remainder.

Example - 1:

print( 3 % 2 )


OUTPUT: 1

Example - 2:

print( 12 % 2 )


OUTPUT: 0

Related Links: