Mathematical Operations in Python#

This notebook covers basic mathematical operations in Python. We’ll explore arithmetic operators, order of operations, and some built-in mathematical functions.

Let’s start with basic arithmetic operations. Python supports addition, subtraction, multiplication, and division.

print(5 + 3)  # Addition
print(10 - 4)  # Subtraction
print(6 * 2)  # Multiplication
print(15 / 3)  # Division
8
6
12
5.0

Python also supports exponentiation (raising to a power) and modulo operations (remainder after division).

print(2 ** 3)  # Exponentiation: 2 raised to the power of 3
print(17 % 5)  # Modulo: remainder of 17 divided by 5
8
2

Python follows the standard order of operations (PEMDAS). Let’s see how this works with a complex expression.

result = 2 + 3 * 4 - 6 / 2
print(result)
11.0

We can use parentheses to change the order of operations and make our intentions clear.

result_with_parentheses = (2 + 3) * (4 - 6) / 2
print(result_with_parentheses)
-5.0

Python’s math module provides additional mathematical functions. Let’s import it and use some of its functions.

import math

print(math.sqrt(16))  # Square root
print(math.pi)  # Pi constant
print(math.sin(math.pi/2))  # Sine function
4.0
3.141592653589793
1.0

Finally, let’s look at how to round numbers in Python using built-in functions.

print(round(3.7))  # Rounds to the nearest integer
print(math.floor(3.7))  # Rounds down to the nearest integer
print(math.ceil(3.2))  # Rounds up to the nearest integer
4
3
4