➕ Math Operations

Math operations in Python are straightforward and intuitive, using symbols you already know from basic mathematics. Whether you're calculating a tip at a restaurant, determining the area of a room, or processing financial data, Python's arithmetic operators make it easy to perform calculations in your programs.

Python handles math operations naturally, following the same rules you learned in school.

# Basic math operations in Python
print("=== BASIC MATH ===")

# Simple calculations
a = 10
b = 3

print(f"{a} + {b} = {a + b}")       # 13
print(f"{a} - {b} = {a - b}")       # 7
print(f"{a} * {b} = {a * b}")       # 30
print(f"{a} / {b} = {a / b}")       # 3.3333...

🔢 Basic Arithmetic Operators

Python provides all the standard arithmetic operators you need for mathematical calculations. These operators work with numbers and follow the mathematical rules you're familiar with.

# Working with different numbers
print("=== NUMBER TYPES ===")

# Integers (whole numbers)
students = 25
groups = 5
per_group = students / groups
print(f"{students} students in {groups} groups = {per_group} per group")

# Decimals (floats)
price = 19.99
tax_rate = 0.08
tax = price * tax_rate
total = price + tax
print(f"Price: ${price}, Tax: ${tax:.2f}, Total: ${total:.2f}")

🔄 Special Division Operations

Python offers two types of division to handle different mathematical needs. Understanding when to use each type will help you get the exact results you want.

# Different types of division
print("=== DIVISION TYPES ===")

total_items = 17
boxes = 5

# Regular division - gives decimal result
average = total_items / boxes
print(f"Average items per box: {average}")        # 3.4

# Floor division - gives whole number
full_boxes = total_items // boxes
print(f"Full boxes: {full_boxes}")               # 3

# Remainder - what's left over
leftover = total_items % boxes
print(f"Items left over: {leftover}")            # 2

# Check: 17 = (3 * 5) + 2 ✓

⚡ Exponentiation

Python uses the double asterisk (**) for exponentiation (raising numbers to powers). This operator handles both simple squares and complex exponential calculations.

# Working with exponents
print("=== EXPONENTS ===")

# Simple squares
side = 5
area = side ** 2
print(f"Square with side {side} has area {area}")     # 25

# Cubes
edge = 3
volume = edge ** 3
print(f"Cube with edge {edge} has volume {volume}")   # 27

# Square roots (using fractional exponents)
number = 16
square_root = number ** 0.5
print(f"Square root of {number} is {square_root}")   # 4.0

# 10 Powers of
scientific = 10 ** 6
print(f"10^6 = {scientific}")                        # 1000000

📐 Order of Operations

Python follows the standard mathematical order of operations (PEMDAS): Parentheses, Exponents, Multiplication/Division, Addition/Subtraction. Understanding this order helps you write expressions that calculate correctly.

# Order of operations examples
print("=== ORDER OF OPERATIONS ===")

# Without parentheses - follows PEMDAS
result1 = 2 + 3 * 4
print(f"2 + 3 * 4 = {result1}")              # 14 (multiplication first)

# With parentheses - forces addition first
result2 = (2 + 3) * 4
print(f"(2 + 3) * 4 = {result2}")            # 20 (addition first)

# Complex calculation with precedence
result3 = 2 + 3 * 4 ** 2
print(f"2 + 3 * 4 ** 2 = {result3}")         # 50 (4^2=16, 3*16=48, 2+48=50)

# Practical example: discount and tax calculation
price = 100
discount = 0.20
tax = 0.08
final_price = price * (1 - discount) * (1 + tax)
print(f"Final price after 20% discount + 8% tax: ${final_price:.2f}")

📊 Working with Variables

Math operations become powerful when combined with variables. You can store numbers in variables and perform calculations using those variables, making your code flexible and reusable.

# Math with variables
print("=== VARIABLES IN MATH ===")

# Circle calculations
radius = 7
pi = 3.14159

circumference = 2 * pi * radius
area = pi * radius ** 2

print(f"Circle with radius {radius}:")
print(f"  Circumference: {circumference:.2f}")
print(f"  Area: {area:.2f}")

# Temperature conversion
celsius = 25
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C = {fahrenheit}°F")

# Compound interest calculation
principal = 1000
rate = 0.05  # 5% annual rate
years = 2
amount = principal * (1 + rate) ** years
print(f"${principal} at {rate*100}% for {years} years = ${amount:.2f}")

🔄 Common Math Patterns

Certain mathematical patterns appear frequently in programming. Learning these patterns will help you recognize and implement common calculations more efficiently.

# Common math patterns
print("=== COMMON PATTERNS ===")

# Updating values with shortcuts
score = 100
score += 25      # Add bonus points
score *= 1.1     # 10% bonus multiplier
print(f"Final score: {score:.1f}")

# Percentage calculations
total_questions = 50
correct_answers = 42
percentage = (correct_answers / total_questions) * 100
print(f"Grade: {percentage:.1f}%")

# Unit conversion
miles = 26.2  # Marathon distance
kilometers = miles * 1.60934
print(f"{miles} miles = {kilometers:.1f} kilometers")

# Check if number is even using modulus
number = 42
is_even = number % 2 == 0
print(f"{number} is even: {is_even}")

➕ Quick Math Practice

Let's practice using Python's arithmetic operators with simple calculations!

Hands-on Exercise

Practice basic arithmetic operations including addition, subtraction, multiplication, division, and exponents.

python
# Math Practice - Simple calculations!

# Calculate a pizza order
pizza_price = 12.99
num_pizzas = 3
tax_rate = 0.08

# Calculate costs
subtotal = # TODO: Your code here (pizza_price * num_pizzas)
tax = # TODO: Your code here (subtotal * tax_rate)
total = # TODO: Your code here (subtotal + tax)

# Calculate how much each person pays (4 people)
per_person = # TODO: Your code here (total / 4)

print(f"Subtotal: ${subtotal:.2f}")
print(f"Tax: ${tax:.2f}")
print(f"Total: ${total:.2f}")
print(f"Per person: ${per_person:.2f}")

Solution and Explanation 💡

Click to see the complete solution
# Math Practice - Simple solution

# Calculate a pizza order
pizza_price = 12.99
num_pizzas = 3
tax_rate = 0.08

# Calculate costs
subtotal = pizza_price * num_pizzas    # Multiplication
tax = subtotal * tax_rate              # Multiplication
total = subtotal + tax                 # Addition

# Calculate how much each person pays (4 people)
per_person = total / 4                 # Division

print(f"Subtotal: ${subtotal:.2f}")
print(f"Tax: ${tax:.2f}")
print(f"Total: ${total:.2f}")
print(f"Per person: ${per_person:.2f}")

Key Learning Points:

  • 📌 Multiplication (*): Used to calculate costs
  • 📌 Addition (+): Used to add subtotal and tax
  • 📌 Division (/): Used to split costs equally
  • 📌 Order of operations: Python follows math rules automatically

📚 Math Operations Reference

OperatorNameExampleResult
+Addition5 + 38
-Subtraction5 - 32
*Multiplication5 * 315
/Division5 / 31.6667
//Floor Division5 // 31
%Modulus5 % 32
**Exponentiation5 ** 3125

Understanding these basic math operations prepares you for comparing values and converting types. Math operations are also fundamental to working with lists and function development.

Test Your Knowledge

🚀 What's Next?

Now that you've mastered basic math operations, you're ready to learn about making comparisons between values. Math operations often work together with comparison operators to create powerful decision-making logic.

In the next lesson, we'll explore Comparing Values, where you'll learn how to compare numbers and make decisions based on mathematical relationships.

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent