Python is excellent at math! Let's learn the basic arithmetic operators.
+)print(5 + 3) # 8
print(10 + 2.5) # 12.5-)print(10 - 3) # 7
print(5.5 - 2.5) # 3.0*)print(6 * 7) # 42
print(3.5 * 2) # 7.0/)print(10 / 2) # 5.0
print(15 / 4) # 3.75Note: Division always returns a decimal (float), even if the result is a whole number!
apples = 10
oranges = 5
total_fruit = apples + oranges
print(total_fruit) # 15You can update variables with math:
score = 100
score = score + 10 # add 10 to current score
print(score) # 110Python follows standard math rules (PEMDAS):
result = 2 + 3 * 4
print(result) # 14 (not 20!)
# 3 * 4 = 12, then 2 + 12 = 14Use parentheses to control order:
result = (2 + 3) * 4
print(result) # 20
# 2 + 3 = 5, then 5 * 4 = 20temperature = -5
print(temperature)change = temperature + 10
print(change) # 5
# item prices
shirt = 25.99
pants = 45.00
shoes = 89.99
# calculate subtotal
subtotal = shirt + pants + shoes
print("Subtotal:", subtotal)
# calculate 8% tax
tax = subtotal * 0.08
print("Tax:", tax)
# calculate total
total = subtotal + tax
print("Total:", total)Forgetting parentheses:
# wrong
result = 100 + 50 / 2 # 125.0 not 75!
# right
result = (100 + 50) / 2 # 75.0Dividing by zero:
# this will cause an error!
print(10 / 0)Now that you can do math, learn about F-Strings and Formatting to display your results nicely!