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:
Python uses symbols for mathematical operations, just like a calculator. Here are the basic operators:
+
Addition: 5 + 3 = 8
-
Subtraction: 10 - 4 = 6
*
Multiplication: 6 * 7 = 42
/
Division: 15 / 3 = 5.0
(always gives decimal result)//
Floor Division: 15 // 4 = 3
(whole number result)%
Modulo: 15 % 4 = 3
(remainder after division)**
Exponentiation: 2 ** 3 = 8
(2 to the power of 3)# 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.
Create a simple calculator that performs all basic operations on two numbers: 24 and 7. Print each operation with its result.
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)
Convert 200 seconds into minutes and seconds. Use floor division to get whole minutes and modulo to get remaining seconds.
Python follows the same order of operations as mathematics (PEMDAS):
()
- calculated first**
- calculated next*
, /
, //
, %
- left to right+
, -
- left to rightUse 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)
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)
.
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:
+=
Add and assign: x += 5
means x = x + 5
-=
Subtract and assign: x -= 3
means x = x - 3
*=
Multiply and assign: x *= 2
means x = x * 2
/=
Divide and assign: x /= 4
means x = x / 4
**=
Power and assign: x **= 2
means x = x ** 2
# 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)
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.
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)
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.
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!
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.
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))
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.
Congratulations! You now know how to perform mathematical operations in Python:
+
, -
, *
, /
, //
, %
, **
+=
, -=
, *=
, /=
for shortcutsMath 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!
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!