Skip to main content

Mathematical Operators

Introduction​

Mathematical operators allow us to perform calculations on numbers. These include basic arithmetic, working with remainders, exponents, and updating variables with assignment operators.

Python has two main numeric types: int (integers with arbitrary precision) and float (floating-point numbers with double precision). Python automatically handles the distinction between integers and floats, and performs type promotion when needed.

Python's arithmetic operators are intuitive and powerful, supporting operations like integer division, modulus, and exponentiation.


Concepts​

Arithmetic​

  • + addition
  • - subtraction
  • * multiplication
  • / division (always returns float)
  • // floor division (integer division)
  • % remainder (modulus)
  • ** exponentiation

Assignment Operators​

  • = assignment
  • +=, -=, *=, /=, //=, %=, **= update a variable in place

Mathematical Functions​

  • abs() absolute value
  • round() rounding
  • pow() exponentiation (alternative to **)
  • divmod() returns quotient and remainder

Examples​

a, b = 10, 3
print(a + b) # 13
print(a / b) # 3.3333333333333335
print(a // b) # 3 (floor division)
print(a % b) # 1
print(a ** b) # 1000

# Assignment operators
x = 5
x += 3 # x = x + 3
print(x) # 8

x *= 2 # x = x * 2
print(x) # 16

# Mathematical functions
print(abs(-5)) # 5
print(round(3.14159, 2)) # 3.14
print(pow(2, 3)) # 8
print(divmod(17, 5)) # (3, 2) - quotient and remainder

Challenges​

1. Calculate area of rectangle​

  • Write a program to calculate the area of a rectangle with length = 8 and width = 5.
💡 Show Answer
length, width = 8, 5
area = length * width
print(f"Area: {area}") # 40

2. Find the remainder of 23 ÷ 6​

💡 Show Answer
quotient = 23 // 6
remainder = 23 % 6
print(f"23 ÷ 6 = {quotient} remainder {remainder}") # 3 remainder 5

3. Compute 3⁴​

  • Use ** to calculate 3 to the power of 4.
💡 Show Answer
result = 3 ** 4
print(f"3^4 = {result}") # 81

# Alternative using pow()
result2 = pow(3, 4)
print(f"pow(3, 4) = {result2}") # 81

4. Celsius to Fahrenheit​

  • Write a temperature converter that converts 25°C into Fahrenheit using the formula F = (C × 9/5) + 32.
💡 Show Answer
celsius = 25
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C = {fahrenheit}°F") # 25°C = 77.0°F

# As a function
def celsius_to_fahrenheit(c):
return (c * 9/5) + 32

print(f"0°C = {celsius_to_fahrenheit(0)}°F") # 32.0°F
print(f"100°C = {celsius_to_fahrenheit(100)}°F") # 212.0°F

5. Add prices and apply discount​

  • Simulate a shopping cart: add three item prices, then apply a 15% discount using *=.
💡 Show Answer
item1, item2, item3 = 100, 50, 20
total = item1 + item2 + item3
print(f"Original total: ${total}")

# Apply 15% discount
total *= 0.85 # same as total = total * 0.85
print(f"After 15% discount: ${total}") # $144.5

6. Integer vs float division​

  • Demonstrate the difference between / and // operators.
💡 Show Answer
a, b = 17, 5

print(f"{a} / {b} = {a / b}") # 17 / 5 = 3.4 (float division)
print(f"{a} // {b} = {a // b}") # 17 // 5 = 3 (floor division)
print(f"{a} % {b} = {a % b}") # 17 % 5 = 2 (remainder)

# Using divmod for both quotient and remainder
quotient, remainder = divmod(a, b)
print(f"divmod({a}, {b}) = ({quotient}, {remainder})")

7. Dozens of eggs in 50​

  • Use // and % to calculate how many full dozens (12s) fit into 50 eggs, and how many are left over.
💡 Show Answer
eggs = 50
dozens = eggs // 12
leftover = eggs % 12
print(f"{eggs} eggs = {dozens} dozens + {leftover} eggs")

# Using divmod
dozens, leftover = divmod(eggs, 12)
print(f"Using divmod: {dozens} dozens + {leftover} eggs")

8. Factorial calculator​

  • Create a factorial calculator using a for loop and multiplication.
💡 Show Answer
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result

print(f"5! = {factorial(5)}") # 120
print(f"10! = {factorial(10)}") # 3628800

# Using math module (alternative)
import math
print(f"math.factorial(5) = {math.factorial(5)}")

9. Random number generator​

  • Build a program that generates a random number between 1-6 (dice roll) using the random module.
💡 Show Answer
import random

def roll_dice():
return random.randint(1, 6)

print(f"Dice roll: {roll_dice()}")

# Multiple rolls
rolls = [roll_dice() for _ in range(5)]
print(f"5 rolls: {rolls}")

# Alternative using random.random()
def roll_dice_alt():
return int(random.random() * 6) + 1

print(f"Alternative roll: {roll_dice_alt()}")

10. Compound interest​

  • Write a function compound_interest(principal, rate, years) that returns the total amount after compounding yearly.
💡 Show Answer
def compound_interest(principal, rate, years):
"""Calculate compound interest: A = P(1 + r)^t"""
return principal * (1 + rate) ** years

# Example calculations
principal = 1000
rate = 0.05 # 5%
years = 10

final_amount = compound_interest(principal, rate, years)
interest_earned = final_amount - principal

print(f"Principal: ${principal}")
print(f"Rate: {rate * 100}%")
print(f"Years: {years}")
print(f"Final amount: ${final_amount:.2f}")
print(f"Interest earned: ${interest_earned:.2f}")

# Test with different scenarios
scenarios = [
(1000, 0.05, 10), # Conservative
(1000, 0.07, 20), # Moderate
(5000, 0.03, 5), # Low risk
]

for p, r, y in scenarios:
amount = compound_interest(p, r, y)
print(f"${p} at {r*100}% for {y} years = ${amount:.2f}")