Python: Zero to Hero
Home/The Foundation
Share

Chapter 3: Calculations and Operators

In Chapter 2 you stored numbers in variables. Now you'll put them to work.

Python is an extraordinary calculator. It handles basic arithmetic, follows the right order of operations, gives you shortcuts for common patterns, and comes with built-in tools for rounding, finding extremes, and doing advanced math. By the end of this chapter you'll be able to write programs that compute real things — prices, discounts, averages, distances.

The Seven Arithmetic Operators

Python has seven operators for working with numbers. Let's go through all of them.

Addition, Subtraction, Multiplication, Division

These four work exactly as you'd expect.

print(10 + 3)   # 13
print(10 - 3)   # 7
print(10 * 3)   # 30
print(10 / 3)   # 3.3333333333333335

One thing to notice: dividing two integers with / always gives you a float, even if the result is a whole number.

print(10 / 2)   # 5.0  (not 5)

Floor Division (//)

Floor division divides and then rounds down to the nearest whole number. It always gives you an integer (if both inputs are integers).

print(10 // 3)   # 3   (not 3.33...)
print(17 // 5)   # 3
print(20 // 4)   # 5

This is useful when you need a whole number result — for example, figuring out how many full boxes fit in a truck.

items = 47
box_size = 10
full_boxes = items // box_size
print(full_boxes)   # 4

Modulo (%) — The Remainder

The modulo operator gives you the remainder after division.

print(10 % 3)   # 1   (10 divided by 3 is 3, remainder 1)
print(17 % 5)   # 2   (17 divided by 5 is 3, remainder 2)
print(20 % 4)   # 0   (20 divided by 4 is exactly 5, no remainder)

Two classic uses: checking if a number is even or odd, and figuring out leftovers.

# Even or odd?
number = 7
print(number % 2)   # 1 means odd, 0 means even
# Leftovers after packing boxes
items = 47
box_size = 10
leftover = items % box_size
print(leftover)   # 7 items left over

Exponentiation (**) — Powers

** raises a number to a power.

print(2 ** 3)    # 8   (2 x 2 x 2)
print(5 ** 2)    # 25  (5 squared)
print(9 ** 0.5)  # 3.0 (square root of 9)

That last one is a neat trick: raising to the power of 0.5 gives you the square root.

In plain English: Think of ** as "to the power of." 2 ** 10 means 2 to the power of 10, which is 1024.

Your turn: Calculate how many seconds are in a week using only multiplication. (Hint: 60 seconds x 60 minutes x 24 hours x 7 days.) Store the result in a variable called seconds_in_a_week and print it.

Order of Operations

Python follows the same order of operations you learned in school: exponentiation first, then multiplication and division, then addition and subtraction. If you've seen the acronym PEMDAS or BODMAS, that's what this is.

print(2 + 3 * 4)    # 14, not 20 — multiplication happens first
print((2 + 3) * 4)  # 20 — parentheses force addition first

When in doubt, use parentheses. They make your intention clear and remove any ambiguity.

# Ambiguous
result = 100 - 20 / 4 + 5 * 2

# Clear
result = 100 - (20 / 4) + (5 * 2)
print(result)   # 100 - 5.0 + 10 = 105.0

A real example: calculating a discounted price with tax.

original_price = 200
discount = 30
tax_rate = 0.08

final_price = (original_price - discount) * (1 + tax_rate)
print(final_price)   # 183.6

Without the parentheses, the math would be wrong. With them, it's obvious what happens: subtract the discount first, then apply the tax.

Your turn: Write a program that calculates the area of a rectangle (length x width) and the area of a circle (pi x radius^2). Use 3.14159 for pi. Store each result in a variable and print it.

Using Variables in Calculations

Variables make calculations reusable and readable. Instead of hardcoding numbers, you name them.

hourly_rate = 25.0
hours_worked = 40
weekly_pay = hourly_rate * hours_worked

print(f"Weekly pay: ${weekly_pay}")

Output:

Weekly pay: $1000.0

Now if the hourly rate changes, you only update one line. The calculation stays the same.

You can also use a variable's own value to update it:

score = 50
score = score + 10   # take the old value, add 10, store the result back
print(score)         # 60

This is a very common pattern — you'll use it constantly in loops.

Augmented Assignment Operators

Because updating a variable with its own value is so common, Python gives you a shorthand.

Long form Short form Meaning
x = x + 5 x += 5 add 5 to x
x = x - 5 x -= 5 subtract 5 from x
x = x * 5 x *= 5 multiply x by 5
x = x / 5 x /= 5 divide x by 5
x = x // 5 x //= 5 floor-divide x by 5
x = x % 5 x %= 5 replace x with x mod 5
x = x ** 5 x **= 5 raise x to the power 5
lives = 3
print(lives)   # 3

lives -= 1
print(lives)   # 2

lives -= 1
print(lives)   # 1
price = 100.0
price *= 1.15   # apply 15% markup
print(price)    # 115.0

Your turn: Start with a variable balance = 1000. Apply these operations one at a time, printing after each: add 250, subtract 75, multiply by 1.05 (5% interest), floor-divide by 1. What's the final balance?

Integer vs Float in Calculations

When you mix integers and floats in a calculation, Python always returns a float.

print(5 + 2.0)    # 7.0   (not 7)
print(10 * 0.5)   # 5.0
print(9 / 3)      # 3.0   (division always returns float)
print(9 // 3)     # 3     (floor division returns int if both inputs are int)

This rarely causes problems, but it's good to know. If you need a guaranteed integer, wrap the result in int().

result = int(9 / 3)
print(result)        # 3
print(type(result))  # <class 'int'>

Built-in Math Functions

Python comes with several built-in functions for common math operations — no import needed.

abs() — Absolute Value

Returns the positive version of a number.

print(abs(-42))    # 42
print(abs(42))     # 42
print(abs(-3.14))  # 3.14

Useful for things like finding the distance between two points (distance is always positive).

point_a = 10
point_b = 35
distance = abs(point_a - point_b)
print(distance)   # 25

round() — Rounding

Rounds a float to the nearest integer, or to a specified number of decimal places.

print(round(3.7))       # 4
print(round(3.2))       # 3
print(round(3.14159, 2))  # 3.14
print(round(3.14159, 4))  # 3.1416

The second argument to round() is optional — it tells Python how many decimal places to keep.

price = 19.9999
print(f"${round(price, 2)}")   # $20.0

min() and max() — Smallest and Largest

min() returns the smallest value, max() returns the largest.

print(min(4, 7, 2, 9, 1))   # 1
print(max(4, 7, 2, 9, 1))   # 9

You can also compare two variables:

score_alice = 88
score_bob = 94

winner_score = max(score_alice, score_bob)
print(f"Top score: {winner_score}")   # Top score: 94

pow() — Power (alternative to **)

pow(base, exponent) does the same as base ** exponent.

print(pow(2, 8))   # 256
print(2 ** 8)      # 256  — same result

You'll see both in real code. ** is more common.

Your turn: You have five test scores: 72, 88, 95, 61, 80. Find the highest score, the lowest score, and the rounded average. Store each in a variable and print them with f-strings.

The math Module

For more advanced math, Python has a built-in module called math. You load it with one line at the top of your file.

import math

Then you can use math. followed by the function name.

Square Roots

import math

print(math.sqrt(25))    # 5.0
print(math.sqrt(144))   # 12.0
print(math.sqrt(2))     # 1.4142135623730951

Ceiling and Floor

math.ceil() rounds up to the next integer. math.floor() rounds down.

import math

print(math.ceil(3.1))    # 4
print(math.ceil(3.9))    # 4
print(math.floor(3.9))   # 3
print(math.floor(3.1))   # 3

This is different from round(), which goes to the nearest value. ceil always goes up. floor always goes down.

Real use: you're packaging 47 items into boxes of 6. How many boxes do you need?

import math

items = 47
box_size = 6
boxes_needed = math.ceil(items / box_size)
print(boxes_needed)   # 8  (you can't have a partial box)

Pi and Euler's Number

import math

print(math.pi)    # 3.141592653589793
print(math.e)     # 2.718281828459045
import math

radius = 5
area = math.pi * radius ** 2
print(round(area, 2))   # 78.54

Logarithms and Trigonometry

import math

print(math.log(100, 10))   # 2.0  (log base 10 of 100)
print(math.log(math.e))    # 1.0  (natural log of e)

print(math.sin(math.pi / 2))   # 1.0
print(math.cos(0))              # 1.0

You won't need these often as a beginner, but they're there when you do.

Your turn: Use the math module to calculate the hypotenuse of a right triangle with sides 3 and 4. (Hint: math.sqrt(3**2 + 4**2)). The answer should be 5.0.

A Real-World Example: Shopping Calculator

Let's combine everything from this chapter into one small program.

import math

item_name = "Wireless Headphones"
original_price = 149.99
discount_percent = 20
tax_rate = 0.08

# Apply discount
discount_amount = original_price * (discount_percent / 100)
discounted_price = original_price - discount_amount

# Apply tax
final_price = discounted_price * (1 + tax_rate)

# Round to 2 decimal places
final_price = round(final_price, 2)

print(f"Item:           {item_name}")
print(f"Original price: ${original_price}")
print(f"Discount:       {discount_percent}% (${round(discount_amount, 2)})")
print(f"After discount: ${round(discounted_price, 2)}")
print(f"Tax ({int(tax_rate * 100)}%):      ${round(final_price - discounted_price, 2)}")
print(f"Final price:    ${final_price}")

Output:

Item:           Wireless Headphones
Original price: $149.99
Discount:       20% ($30.0)
After discount: $119.99
Tax (8%):       $9.6
Final price:    $129.59

Real math. Real output. Everything you've learned so far, working together.

Your turn: Modify this program to use your own item, price, and discount. Try changing the tax rate to 0.10 (10%) and see what happens to the final price.

What You Learned in This Chapter

  • Python has 7 arithmetic operators: +, -, *, /, //, %, **
  • / always returns a float. // returns the whole-number part of a division.
  • % gives the remainder — great for checking if a number is even or odd.
  • ** raises to a power. 9 ** 0.5 gives the square root.
  • Python follows PEMDAS order. Use parentheses to be explicit.
  • Augmented operators (+=, -=, *=, /=, etc.) update a variable using its own value.
  • Mixing an int and a float in a calculation gives you a float.
  • Built-in functions: abs(), round(), min(), max(), pow()
  • The math module: sqrt(), ceil(), floor(), pi, e, log(), trig functions.

What's Next?

So far your programs run straight through from top to bottom. They don't make decisions — they just calculate.

In Chapter 4, you'll change that. You'll use if, elif, and else to make programs that do different things depending on conditions. Is the score above 50? Print "Pass." Is it below? Print "Fail." Your programs are about to get a lot more interesting.

Your turn: Before moving on, write a program that takes a circle's radius (store it in a variable), then calculates and prints: the area (pi x r^2), the circumference (2 x pi x r), and the diameter (2 x r). Round all results to 2 decimal places. Use the math module for pi.

© 2026 Abhilash Sahoo. Python: Zero to Hero.