Math Operations - Making Python Your Calculator

Python is an excellent calculator! You can perform all sorts of mathematical operations, from simple addition to complex calculations. In programming, we use math constantly - calculating totals, figuring out percentages, counting items, and much more.

In this lesson, you'll learn:

1. Basic Math Operators

Python uses symbols for mathematical operations, just like a calculator. Here are the basic operators:

# Basic arithmetic operations
a = 10
b = 3

addition = a + b
subtraction = a - b
multiplication = a * b
division = a / b
floor_division = a // b
remainder = a % b
power = a ** b

print("a =", a, "and b =", b)
print("Addition:", a, "+", b, "=", addition)
print("Subtraction:", a, "-", b, "=", subtraction)
print("Multiplication:", a, "*", b, "=", multiplication)
print("Division:", a, "/", b, "=", division)
print("Floor division:", a, "//", b, "=", floor_division)
print("Remainder:", a, "%", b, "=", remainder)
print("Power:", a, "**", b, "=", power)

Notice the difference between regular division (/) and floor division (//). Regular division always gives a decimal number, while floor division gives the whole number part only.

Exercise: Basic Calculator

Create a simple calculator that performs all basic operations on two numbers: 24 and 7. Print each operation with its result.

# TODO: Create variables num1 = 24 and num2 = 7 # TODO: Print addition: "24 + 7 = result" # TODO: Print subtraction: "24 - 7 = result" # TODO: Print multiplication: "24 * 7 = result" # TODO: Print division: "24 / 7 = result"

2. Understanding Modulo and Floor Division

The modulo (%) and floor division (//) operators are extremely useful in programming:

# Understanding modulo with examples
print("Modulo examples (remainder after division):")
print("10 % 3 =", 10 % 3, "(10 divided by 3 is 3 remainder 1)")
print("15 % 4 =", 15 % 4, "(15 divided by 4 is 3 remainder 3)")
print("20 % 5 =", 20 % 5, "(20 divided by 5 is 4 remainder 0)")

# Checking if numbers are even or odd
number = 7
if_even_remainder = number % 2
print("Number:", number, "Remainder when divided by 2:", if_even_remainder)

number = 8
if_even_remainder = number % 2
print("Number:", number, "Remainder when divided by 2:", if_even_remainder)

print()
print("Floor division examples (whole number part):")
print("17 // 5 =", 17 // 5, "(17 divided by 5 is 3.4, whole part is 3)")
print("25 // 7 =", 25 // 7, "(25 divided by 7 is 3.57..., whole part is 3)")

# Converting minutes to hours and minutes
total_minutes = 150
hours = total_minutes // 60
remaining_minutes = total_minutes % 60
print("Total minutes:", total_minutes)
print("Hours:", hours, "Remaining minutes:", remaining_minutes)

Exercise: Time Conversion

Convert 200 seconds into minutes and seconds. Use floor division to get whole minutes and modulo to get remaining seconds.

# TODO: Create a variable total_seconds = 200 # TODO: Calculate minutes using floor division (total_seconds // 60) # TODO: Calculate remaining seconds using modulo (total_seconds % 60) # TODO: Print the results as shown in expected output

3. Order of Operations

Python follows the same order of operations as mathematics (PEMDAS):

  1. Parentheses: () - calculated first
  2. Exponents: ** - calculated next
  3. Multiplication and Division: *, /, //, % - left to right
  4. Addition and Subtraction: +, - - left to right

Use parentheses to make your intentions clear, even when not strictly necessary!

# Order of operations examples
result1 = 2 + 3 * 4
result2 = (2 + 3) * 4
result3 = 2 ** 3 + 1
result4 = 2 ** (3 + 1)

print("2 + 3 * 4 =", result1, "(multiplication first)")
print("(2 + 3) * 4 =", result2, "(parentheses first)")
print("2 ** 3 + 1 =", result3, "(exponent first)")
print("2 ** (3 + 1) =", result4, "(parentheses first)")

Here's a practical example with the area of a circle:

# Complex calculation: area of a circle
radius = 5
pi = 3.14159
area_wrong = pi * radius ** 2  # Correct: exponent before multiplication
area_clear = pi * (radius ** 2)  # Even clearer with parentheses

print("Circle radius:", radius)
print("Area calculation: pi * radius ** 2 =", area_wrong)
print("Same with parentheses: pi * (radius ** 2) =", area_clear)

Exercise: Practice Order of Operations

Calculate the result of this expression step by step: 3 + 4 * 2 ** 2 - 1. Also calculate what it would be with different parentheses: (3 + 4) * 2 ** (2 - 1).

# TODO: Calculate 3 + 4 * 2 ** 2 - 1 and store in result1 # TODO: Calculate (3 + 4) * 2 ** (2 - 1) and store in result2 # TODO: Print both expressions and their results

4. Assignment Operators - Shortcuts for Updating Variables

Very often in programming, you want to update a variable based on its current value. Instead of writing x = x + 5, Python provides shortcuts called assignment operators:

# Starting value
score = 10
print("Starting score:", score)

# Using assignment operators
score += 5  # Same as: score = score + 5
print("After adding 5:", score)

score -= 3  # Same as: score = score - 3
print("After subtracting 3:", score)

score *= 2  # Same as: score = score * 2
print("After doubling:", score)

score /= 4  # Same as: score = score / 4
print("After dividing by 4:", score)

score **= 2  # Same as: score = score ** 2
print("After squaring:", score)

A common pattern is incrementing a counter:

# Common pattern: incrementing a counter
counter = 0
print("Counter starts at:", counter)

counter += 1
print("After increment:", counter)

counter += 1
print("After another increment:", counter)

Another common pattern is accumulating a total:

# Adding to a total
total = 0
total += 10
total += 25
total += 8
print("Total after adding 10, 25, and 8:", total)

Exercise: Track Bank Account Balance

Start with a bank balance of $1000. Make several transactions: deposit $250, withdraw $75, add 1% interest (multiply by 1.01), then withdraw $100. Print the balance after each transaction.

# TODO: Start with balance = 1000 and print it # TODO: Add 250 to balance and print "After deposit: $ balance" # TODO: Subtract 75 from balance and print "After withdrawal: $ balance" # TODO: Multiply balance by 1.01 and print "After interest: $ balance" # TODO: Subtract 100 from balance and print "Final balance: $ balance"

5. Working with Different Number Types

Python has two main types of numbers:

When you mix integers and floats in calculations, Python usually gives you a float result. Division always gives a float, even if the result is a whole number.

# Different number types
whole_number = 10  # Integer
decimal_number = 3.5  # Float

print("Whole number:", whole_number, "Type:", type(whole_number))
print("Decimal number:", decimal_number, "Type:", type(decimal_number))

# Mixing integers and floats
result1 = whole_number + decimal_number
result2 = whole_number * decimal_number
result3 = whole_number / 2  # Division always gives float

print("10 + 3.5 =", result1, "Type:", type(result1))
print("10 * 3.5 =", result2, "Type:", type(result2))
print("10 / 2 =", result3, "Type:", type(result3))

You can convert between number types:

# Converting between types
whole_number = 10
decimal_number = 3.5

float_result = float(whole_number)  # Convert int to float
int_result = int(decimal_number)    # Convert float to int (truncates)

print("10 as float:", float_result)
print("3.5 as int:", int_result, "(decimal part removed)")

Python provides several ways to round numbers:

# Rounding
import math
rounded_up = math.ceil(3.2)    # Round up
rounded_down = math.floor(3.8)  # Round down
rounded_normal = round(3.7)     # Round to nearest

print("3.2 rounded up:", rounded_up)
print("3.8 rounded down:", rounded_down)
print("3.7 rounded normally:", rounded_normal)

Exercise: Grade Calculator

Calculate a student's average grade from three test scores: 85, 92, and 78. Calculate the average and round it to the nearest whole number.

# TODO: Create variables for three test scores: 85, 92, 78 # TODO: Calculate the total points # TODO: Calculate the average (total / 3) # TODO: Round the average to nearest whole number # TODO: Print all results as shown

6. Practical Math Applications

Let's see how math operations are used in real programming scenarios. These patterns show up everywhere in programming!

# Calculating compound interest
principal = 1000    # Starting amount
rate = 0.05        # 5% interest rate
years = 3          # Time period

# Simple interest: P * r * t
simple_interest = principal * rate * years
simple_total = principal + simple_interest

print("Simple Interest Calculation:")
print("Principal:", principal)
print("Rate:", rate * 100, "%")
print("Years:", years)
print("Interest earned:", simple_interest)
print("Total amount:", simple_total)

print()

# Compound interest: P * (1 + r)^t
compound_total = principal * (1 + rate) ** years
compound_interest = compound_total - principal

print("Compound Interest Calculation:")
print("Principal:", principal)
print("Rate:", rate * 100, "%")
print("Years:", years)
print("Interest earned:", compound_interest)
print("Total amount:", compound_total)

print()
print("Difference:", compound_interest - simple_interest)

This example shows how math operators let you model real-world situations like financial calculations. The ability to raise numbers to powers (**) is crucial for compound interest calculations!

Exercise: Pizza Party Calculator

Calculate how much pizza to order for a party. You have 23 people, each person eats 3 slices on average, and each pizza has 8 slices. Calculate how many pizzas to order and the cost if each pizza costs $12.50.

# TODO: Set people = 23, slices_per_person = 3, slices_per_pizza = 8 # TODO: Calculate total_slices = people * slices_per_person # TODO: Calculate pizzas_needed = total_slices / slices_per_pizza # TODO: Round up to get pizzas_to_order (hint: round(pizzas_needed + 0.5)) # TODO: Calculate total_cost with cost_per_pizza = 12.50 # TODO: Print all the results as shown

🎯 Bring It All Together: Complete Financial Calculator

Let's create a comprehensive example that uses all the math operations we've learned to build a personal finance calculator.

# Personal Finance Calculator
print("=" * 50)
print("PERSONAL FINANCE CALCULATOR")
print("=" * 50)

# Monthly income and expenses
monthly_salary = 4000
bonus = 500
total_income = monthly_salary + bonus

# Monthly expenses
rent = 1200
groceries = 400
utilities = 150
transportation = 300
entertainment = 200

total_expenses = rent + groceries + utilities + transportation + entertainment
monthly_savings = total_income - total_expenses

print("MONTHLY INCOME:")
print("Salary: $", monthly_salary)
print("Bonus: $", bonus)
print("Total income: $", total_income)

print("\nMONTHLY EXPENSES:")
print("Rent: $", rent)
print("Groceries: $", groceries)
print("Utilities: $", utilities)
print("Transportation: $", transportation)
print("Entertainment: $", entertainment)
print("Total expenses: $", total_expenses)

print("\nSAVINGS ANALYSIS:")
print("Monthly savings: $", monthly_savings)

# Calculate percentage savings
savings_percentage = (monthly_savings / total_income) * 100
print("Savings rate:", round(savings_percentage, 1), "%")

# Yearly projections
yearly_savings = monthly_savings * 12
print("Yearly savings: $", yearly_savings)

# Emergency fund goal (6 months of expenses)
emergency_fund_goal = total_expenses * 6
months_to_goal = emergency_fund_goal / monthly_savings

print("\nEMERGENCY FUND:")
print("Goal (6 months expenses): $", emergency_fund_goal)
print("Months to reach goal:", round(months_to_goal, 1))

# Investment growth (assuming 7% annual return)
investment_years = 10
annual_return = 0.07
future_value = yearly_savings * ((1 + annual_return) ** investment_years - 1) / annual_return

print("\nINVESTMENT PROJECTION (10 years at 7%):")
print("Future value: $", round(future_value, 2))

Final Exercise: Unit Conversion Calculator

Create a unit conversion calculator. Convert 100 kilometers to miles (1 km = 0.621371 miles), and convert 75 degrees Fahrenheit to Celsius using the formula: C = (F - 32) * 5/9.

# TODO: Convert 100 kilometers to miles (1 km = 0.621371 miles) # TODO: Convert 75 degrees Fahrenheit to Celsius: C = (F - 32) * 5/9 # TODO: Print results as shown in expected output

📝 What You've Learned

Congratulations! You now know how to perform mathematical operations in Python:

Math operations are fundamental to programming - you'll use them for everything from simple counting to complex algorithms. With these tools, you can make Python solve numerical problems and model real-world situations!

Next Steps

Now that you can store data in variables and perform calculations, you're ready to learn about getting input from users and making your programs interactive!