easycodelearning.com
🐍 Learn Python Online
Back to All Tutorials

Math Operations

Basic Arithmetic Operations

Python can perform mathematical calculations just like a calculator. Here are the basic operations:

Addition (+)

result = 10 + 5
print(result)  # Output: 15

x = 3.5
y = 2.5
print(x + y)  # Output: 6.0

Subtraction (-)

result = 10 - 5
print(result)  # Output: 5

x = 20
y = 8
print(x - y)  # Output: 12

Multiplication (*)

result = 10 * 5
print(result)  # Output: 50

x = 3
y = 4
print(x * y)  # Output: 12

Division (/)

result = 10 / 5
print(result)  # Output: 2.0

x = 15
y = 3
print(x / y)  # Output: 5.0

Floor Division (//)

Divides and rounds down to the nearest integer:

result = 10 // 3
print(result)  # Output: 3

x = 17
y = 5
print(x // y)  # Output: 3

Modulo (%)

Returns the remainder after division:

result = 10 % 3
print(result)  # Output: 1

x = 17
y = 5
print(x % y)  # Output: 2

Exponentiation (**)

Raises a number to a power:

result = 2 ** 3
print(result)  # Output: 8

x = 5
y = 2
print(x ** y)  # Output: 25

Order of Operations (PEMDAS)

Python follows the standard order of operations:

  1. Parentheses: ()
  2. Exponentiation: **
  3. Multiplication, Division: *, /, //, %
  4. Addition, Subtraction: +, -

Examples:

# Without parentheses
result = 2 + 3 * 4
print(result)  # Output: 14 (not 20)

# With parentheses
result = (2 + 3) * 4
print(result)  # Output: 20

# Complex expression
result = 10 + 5 * 2 - 3 / 1
print(result)  # Output: 17.0

Using Variables in Math

length = 10
width = 5
area = length * width
print("Area:", area)  # Output: Area: 50

price = 25.99
quantity = 3
total = price * quantity
print("Total:", total)  # Output: Total: 77.97

Key Takeaways

  • Python supports basic arithmetic: +, -, *, /, //, %, **
  • Follow the order of operations (PEMDAS)
  • Use parentheses to change the order of operations
  • You can use variables in mathematical expressions

Practice Time

Try calculating the area of a rectangle, the total cost of items, or any other math problem using the code editor!

Open Code Editor
Next: Working with Strings