Basic Math Operators

Now that "hello world" is out of the way, let's do some maths.

Python has the standard complement of mathematical operators for addition, subtraction, multiplication, and both integer/floating point division operators. Beyond these, there is a selection of standard library math components, which are greatly expanded on by third-party libraries. more on those later

Addition

print(4 + 3)
# 7
print(-6 + 4 + 2)
# 0

Subtraction

print(12 - 5)
# 7
print(-5 - 7)
# -12

Multiplication

print(22 * 4)
# 88

Division

print(22 / 2)
# 11.0
print(5 / 6)
# 0.8333333333333334
# Note: Exact output may vary slightly.

Integer Division

/ refers to "floating point" division, and produces a decimal output.

print(type(5 / 6))
# <class 'float'>

There are cases where an integer output is instead desirable. For this, python has a second division operator:

print(5 // 6)
# 0
print(type(5 // 6))
# <class 'int'>

Exponentiation

Raising one value to a power of another is achieved using the ** operator.

print(5**2)  # 5 squared.
# 25

# you can also raise values to fractional powers.
print(125**(1/3))
# 4.999999999999999
# Note: exact value may vary slightly due to floating point inaccuracy.

Modulus

The last of the core math operators we will introduce at this point is the modulus operator.


print(15 % 6)
# 3

Note: The modulus of i % j will have the same sign as j.