Remember that old pocket calculator you used to tap nervously during math class?
Python can do everything it could, only smarter, friendlier, and way less judgy when you forget how to divide fractions.
At its heart, Python is a math nerd. It loves numbers, and it can crunch them faster than any human ever could (even the one who invented math). Whether you’re adding up your shopping list, figuring out the tip at a restaurant, or plotting a spaceship trajectory (hey, dream big), Python can handle it all.
The best part? You don’t need any new tools. Just the print() function and a few math symbols you already know: +, -, *, /, and a couple of cool extras we’ll meet soon.
By the end of this lesson, you’ll know how to:
- Use Python like a calculator, no buttons required.
- Do everything from simple addition to real-world budgeting.
- Avoid the common mistakes that make beginners say, “Wait, why is it 4.0 instead of 4?”
So grab your imaginary calculator hat, Python’s about to become your new math buddy.
Python as a Calculator: The Basics
Let’s start with something that’ll make you feel instantly productive:
Python can replace your calculator, and it’s much more fun to use.
Just open Thonny (or any Python editor, like ours) and start typing math directly into your code.
No setup, no imports, no magic words, just type, run, and smile.
Try this:
print(5 + 3)
print(10 - 4)
print(7 * 2)
print(9 / 2)
Output:
8
6
14
4.5
Congratulations, you just used Python as a calculator!
Let’s break down what’s happening:
| Symbol | Operation | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 10 - 4 | 6 |
* | Multiplication | 7 * 2 | 14 |
/ | Division | 9 / 2 | 4.5 |
Notice that division always gives a float (a number with a decimal), even when it divides evenly:
print(8 / 2)
Output:
4.0
Python’s just being cautious. It keeps decimals even when you don’t need them, just in case you do.
Python’s division always comes with a decimal point, it likes to be precisely imprecise.
SuperPyDuck
Fun Fact
Python doesn’t need a calculator app.
It is the calculator app!
SuperPyDuck
Fun Fact
Python doesn’t need a calculator app.
It is the calculator app!
Integer Division and Remainders
Alright, you’ve seen how Python divides numbers, but sometimes, you don’t want the decimals.
Sometimes you just need the whole number or what’s left over after dividing.
Python can do both.
Whole Division with //
If you divide numbers like 9 by 2 normally, Python gives you a float:
print(9 / 2)
Output:
4.5
But if you want only the whole number part of the result, use floor division (//):
print(9 // 2)
Output:
4
Python just chops off the decimal and keeps the whole part.
// is like dividing and then saying, ‘No decimals, please. I’m in a hurry.’
Finding the Remainder with %
Now, what if you want the leftover part instead, the remainder after dividing?
That’s what the modulo operator (%) does.
print(9 % 2)
Output:
1
That’s because 9 divided by 2 is 4 with 1 left over.
Let’s make it fun:
cookies = 10
kids = 3
leftovers = cookies % kids
print(f"Each kid gets {cookies // kids} cookies, and {leftovers} are left over.")
Output:
Each kid gets 3 cookies, and 1 are left over.
Now that’s math you can snack on.
Why It’s Useful
//is great for things like rounding down automatically or dividing items evenly.%is perfect for finding leftovers, rotations, or patterns in code (like checking if a number is even or odd).
Try this:
print(10 % 2) # 0 means even
print(7 % 2) # 1 means odd
Python just became your math teacher.
Exponents and Roots
Now that you’ve mastered adding, subtracting, and dividing like a pro, it’s time to make Python flex its real power muscles: exponents and roots.
These are the operations that let Python handle powers, squares, cubes, and even square roots; the kind of math that made us all wish we had smarter calculators in school.
Raising Numbers to Powers
Python uses the ** operator for exponents, think of it as “to the power of.”
print(2 ** 3)
print(5 ** 2)
print(10 ** 0)
Output:
8
25
1
Explanation:
2 ** 3= 2 × 2 × 2 = 85 ** 2= 25 (that’s 5 squared)Anything raised to the power of 0 becomes
1, that’s math magic, not a bug.
The ** operator is like giving a number a caffeine boost, it multiplies itself until it feels powerful enough.
Finding Roots
You can also use exponents backwards to find square roots, cube roots, and more.
print(9 ** 0.5) # Square root of 9
print(27 ** (1/3)) # Cube root of 27
print(256 ** 0.25) # Fourth root of 256
Output:
3.0
3.0
4.0
So, what’s happening?
Python sees exponents with fractions like “power of ½” and calculates the root.
So x ** 0.5 means “square root of x,” and x ** (1/3) means “cube root of x.”
Why This Is Awesome
You can do scientific calculations with no extra tools.
You can build math-heavy programs like games, physics simulations, or budget apps that calculate percentages and interest.
You can finally stop pretending you remember how to use a graphing calculator.
Order of Operations (PEMDAS)
Here’s something that trips up every beginner (and a few pros, too):
Python follows the same order of operations as regular math, but if you forget that, your results can get… creative.
Let’s test it:
print(2 + 3 * 4)
Output:
14
Wait, shouldn’t that be 20? Nope.
Python multiplied 3 * 4 first (because multiplication comes before addition) and then added 2.
If you wanted it to do the addition first, you’d use parentheses:
print((2 + 3) * 4)
Output:
20
Python follows a strict order, and the magic word to remember it is PEMDAS.
The PEMDAS Rule
| Letter | Stands For | Example | Result |
|---|---|---|---|
| P | Parentheses | (2 + 3) * 4 | 20 |
| E | Exponents | 2 ** 3 | 8 |
| M | Multiplication | 3 * 4 | 12 |
| D | Division | 12 / 3 | 4.0 |
| A | Addition | 5 + 2 | 7 |
| S | Subtraction | 9 - 3 | 6 |
That’s the order Python always follows: from top to bottom, left to right (within each level).
Python doesn’t guess what you meant, it does exactly what you wrote. This is highly exemplified when playing with numbers with Python.
Practice Time
Try guessing these before you run them:
print(10 - 3 * 2) # ?
print((10 - 3) * 2) # ?
print(2 ** 3 * 2) # ?
print(2 ** (3 * 2)) # ?
Then run them in Thonny and check if you predicted correctly.
Understanding order of operations makes you a smarter coder, and helps you avoid those “Python betrayed me” moments.
Real-Life Math Examples
Alright, let’s take all this math and numbers magic and use it for something useful, the kind of stuff you could actually do in everyday life.
Python isn’t just a playground for numbers, it’s a calculator that remembers, explains, and formats your results exactly how you want.
Example 1: Daily Budget
Let’s say you’re tracking how much you spend in a day.
Coffee, lunch, and transport, all the essentials of being human.
coffee = 5.5
lunch = 12
transport = 4.25
total = coffee + lunch + transport
print(f"Today's expenses: ${total}")
Output:
Today's expenses: $21.75
Simple, but powerful.
Python read the numbers, did the math and made it human-readable. No Excel formulas, no calculator buttons.
Example 2: Currency Conversion
Let’s say you’ve got some dollars and want to see how much that is in Danish kroner.
usd = 50
rate = 6.8
dkk = usd * rate
print(f"{usd} USD is {dkk} DKK.")
Output:
50 USD is 340.0 DKK.
You can even go the other way:
dkk = 1000
rate = 0.15
usd = dkk * rate
print(f"{dkk} DKK is {usd} USD.")
Python just became your own personal currency converter.
Example 3: Trip Cost Estimator
Need to calculate fuel costs for a short trip? No problem.
distance = 120 # miles
fuel_efficiency = 15 # miles per gallon
fuel_price = 12.5 # $ per gallon
liters_needed = distance / fuel_efficiency
total_cost = liters_needed * fuel_price
print(f"Total fuel cost for {distance} miles: ${total_cost}")
Output:
Total fuel cost for 120 miles: $100.0
It’s like having your own road trip assistant, minus the bad playlist choices.
Example 4: Party Pizza Math
Planning a small party? Let Python handle the slicing logic.
pizzas = 3
slices_per_pizza = 8
guests = 10
total_slices = pizzas * slices_per_pizza
slices_each = total_slices // guests
leftovers = total_slices % guests
print(f"Each guest gets {slices_each} slices, and {leftovers} are left over.")
Output:
Each guest gets 2 slices, and 4 are left over.
Python is like that one friend who’s weirdly good at splitting the bill.
Using the math Module
Okay, you’ve learned how to do all the basic arithmetic — but what if you want to get fancy?
You know, stuff like square roots, rounding, or using π (pi) without typing 3.1415926 by hand?
That’s where Python’s built-in math module comes in.
Think of it as an extra toolbox you can open whenever you want to do more advanced calculations.
Step 1: Bring It Into Your Program
Before using it, you have to import it:
import math
That one line tells Python: “Hey, grab your calculator backpack, we’re doing real math now.”
Step 2: Use Its Tools
Here are some of the most useful math functions for beginners:
import math
print(math.sqrt(16)) # Square root
print(math.pi) # Pi constant
print(math.ceil(2.3)) # Round up
print(math.floor(2.9)) # Round down
print(math.pow(2, 3)) # 2 to the power of 3
Output:
4.0
3.141592653589793
3
2
8.0
Let’s break them down:
math.sqrt(x)→ square root of xmath.pi→ the exact value of πmath.ceil(x)→ rounds up to the nearest integermath.floor(x)→ rounds down to the nearest integermath.pow(a, b)→ a raised to the power of b (like**, but always returns a float)
Step 3: Real Example - Circle Math
Let’s calculate the area and circumference of a pizza (or a planet, depending on your appetite).
import math
radius = 5
area = math.pi * (radius ** 2)
circumference = 2 * math.pi * radius
print(f"Area: {area}")
print(f"Circumference: {circumference}")
Output:
Area: 78.53981633974483
Circumference: 31.41592653589793
You just used Python to do geometry. Congratulations, you’re now smarter than your high school self!
Pro Tip: Why We Import
The reason math isn’t always loaded automatically is simple: Python tries to stay light.
You only import what you need, like adding toppings to your pizza.
The math module is like a secret pocket calculator Python hides in its feathers.
The Power of Shortcuts
By now, you’ve been writing things like:
score = score + 10
That’s fine, but Python, being the efficient little genius it is, says: “Why type the same thing twice when one symbol can do it?”
That’s where compound assignment operators come in.
They’re shortcuts for updating variables without repeating yourself.
Meet Your New Best Friends
| Shortcut | Long Version | What It Does |
|---|---|---|
x += 5 | x = x + 5 | Add and store the new value |
x -= 3 | x = x - 3 | Subtract and store |
x *= 2 | x = x * 2 | Multiply and store |
x /= 4 | x = x / 4 | Divide and store |
x //= 2 | x = x // 2 | Floor divide and store |
x **= 3 | x = x ** 3 | Raise to a power and store |
x %= 2 | x = x % 2 | Store the remainder |
Example: Leveling Up
score = 10
score += 5
print(score)
score *= 2
print(score)
Output:
15
30
See? It’s cleaner, faster, and easier to read.
These shortcuts are Python’s way of saying, ‘Don’t repeat yourself, I’ve got this.’
Real-Life Example
Let’s say you’re tracking a daily budget:
money = 100
money -= 25 # bought groceries
money -= 15 # coffee and snacks
money += 50 # payday!
print(f"Remaining balance: {money}")
Output:
Remaining balance: 110
You just updated your variable multiple times without repeating the name in full sentences.
Clean, simple, efficient.
Python programmers are lazy, but in the elegant, time-saving kind of way. You know, the smart way.
Common Math Mistakes
Even the smartest ducks (and humans) slip up sometimes when doing math in Python.
The good news? Every mistake is a quick fix once you know what’s going on.
Let’s look at the most common beginner math mix-ups, and how to avoid them.
1. Expecting / to Give an Integer
When you divide with /, Python always gives you a float.
Even if the result is perfectly clean:
print(8 / 2)
Output:
4.0
Fix:
If you only want the whole number, use // instead:
print(8 // 2) # = 4
The single slash is fancy; the double slash is practical.
2. Mixing Strings and Numbers
This one’s a classic:
print("Your total is " + 25)
Python panics:
TypeError: can only concatenate str (not "int") to str
Fix:
Convert the number to a string with str():
print("Your total is " + str(25))
Or use an f-string:
total = 25
print(f"Your total is {total}")
3. Forgetting Parentheses
Sometimes your math works, just not the way you meant.
print(2 + 3 * 4)
Output:
14
Fix:
Use parentheses to control order:
print((2 + 3) * 4) # = 20
Parentheses are like Python’s GPS, they make sure it follows your route, not the default one.
4. Dividing by Zero
print(10 / 0)
Boom:
ZeroDivisionError: division by zero
✅ Fix:
Always check before dividing:
number = 10
divider = 0
if divider != 0:
print(number / divider)
else:
print("Nice try, Frito! You can’t divide by zero.")
Python forgives, but math does not.
5. Forgetting to Import math
You can’t use functions like math.sqrt() or math.pi until you’ve imported the module:
print(math.sqrt(9)) # NameError
Fix:
import math
print(math.sqrt(9)) # Works!
Importing math is like grabbing your toolbox, don’t start hammering without it.
SuperPyDuck
Fun Fact
Most math errors in Python come from one thing:
humans being… human.
SuperPyDuck
Fun Fact
Most math errors in Python come from one thing:
humans being… human.
Mini Challenge: The Python Budget Buddy
It’s time to put your new math powers to work, and make Python handle real-life money problems.
Let’s build your very first “mini app”: The Budget Buddy.
This little project will let you track your daily expenses and calculate your total and average spending, all in pure Python.
Your Mission
Create a new file called budget_buddy.py.
Then follow these steps:
Step 1: Store Your Expenses
Start by storing the prices of three things you bought today:
coffee = 5.5
sandwich = 7.25
book = 12.9
Each variable holds a float, because prices often include decimals.
Step 2: Do the Math
Now, calculate your total and your average cost:
total = coffee + sandwich + book
average = total / 3
Step 3: Make It Talk
Let’s print the results in a friendly way using f-strings:
print(f"Total spent: ${total}")
print(f"Average cost per item: ${average}")
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
Total spent: $25.65
Average cost per item: $8.55
Boom. You just turned raw math into human language.
Step 4: Make It Dynamic (Optional Challenge)
Want to take it up a notch?
Ask the user to enter their own expenses using input():
coffee = float(input("Coffee price: "))
sandwich = float(input("Sandwich price: "))
book = float(input("Book price: "))
total = coffee + sandwich + book
average = total / 3
print(f"Total spent: ${total}")
print(f"Average cost per item: ${average}")
Python now works like a mini budgeting app, powered entirely by your code.
You’ve just written your first practical Python program. It does math, stores data, and talks back. That’s real coding.
Let's Wrap Up: Python, the Math Nerd
ake a moment to appreciate this — you just turned Python into your own personal calculator, budget tracker, and math teacher all in one.
At this point, you’ve learned how to make Python:
- Add, subtract, multiply, and divide like a pro
- Handle whole numbers, floats, and remainders
- Follow math order with perfect discipline (PEMDAS-style)
- Calculate powers, roots, and even circles with the
mathmodule - Use clever shortcuts like
+=and**= Avoid the rookie mistakes that trip up beginners- Build your very first math-based project (Budget Buddy!)
That’s a huge step. You’ve moved from just writing code to actually using it for real-life problems, and that’s when Python starts to feel like a superpower.
A programmer without math is like a duck without water, technically possible, but kind of sad.
You’ve learned how to make Python think with numbers.