A calculator gives you one answer at a time. Python gives you a calculator that remembers values, works with whole lists of numbers at once, never makes arithmetic mistakes, and shows you every step. That makes it the perfect companion for learning maths: you can check every example in this course, change the numbers, and see what happens.
This lesson shows how to use Python for maths, from simple sums to square roots, rounding, fractions and averages. You don't need any programming experience. Each piece of code is short, and the output is shown below it.
What you need first: Python installed, as shown in how to install Python, and a way to run it, from how to run Python code. Reading the maths symbols guide helps, but isn't required.
Key terms
- Code: instructions for the computer, written in a programming language such as Python.
- Output: what the code prints back to you.
- Operator: a symbol that does a calculation, like
+or*. - Variable: a name that stores a value so you can reuse it, like
price = 250. - Module: a collection of extra tools you load with
import, such asmath.
Where to type the code
The quickest way to experiment is Python's interactive mode: open a terminal, type python (or py on Windows), and press Enter. You'll see >>>. Type a calculation, press Enter, and the answer appears straight away.
For longer examples, save the code in a file such as maths.py and run it, or use a notebook such as Jupyter. In a file, wrap results in print() so they appear on screen, as all the examples below do.
The basic operations
print(7 + 3) # add
print(7 - 3) # subtract
print(7 * 3) # multiply
print(7 / 3) # divide
10
4
21
2.3333333333333335
- Python uses
*for multiply and/for divide, because × and ÷ aren't on keyboards. - Anything after
#is a comment: a note for humans that Python ignores. - Division gives a decimal answer even when it divides exactly:
6 / 3is2.0. - The last digit of
2.3333333333333335looks odd. Computers store decimals in binary, which causes tiny rounding errors in the 16th digit. They never matter for data science, but they're why we round results for display.
Order of operations
Python follows the same rules as maths: brackets first, then powers, then multiply and divide, then add and subtract. You'll often see this called BODMAS or PEMDAS.
print(2 + 3 * 4) # multiply first: 2 + 12
print((2 + 3) * 4) # brackets first: 5 * 4
print(10 - 4 / 2) # divide first: 10 - 2
14
20
8.0
When in doubt, add brackets. They make your meaning clear to Python and to anyone reading your code.
Powers and roots
print(3 ** 2) # 3 squared
print(2 ** 10) # 2 to the power 10
print(9 ** 0.5) # square root, as a power of one half
print(10 ** -2) # a negative power: 1 / 100
9
1024
3.0
0.01
** means "to the power of". Don't use ^: in Python it means something completely different, and 3 ^ 2 gives 1, not 9.
Whole-number division and remainders
print(17 // 5) # how many whole 5s fit into 17
print(17 % 5) # the remainder
3
2
17 ÷ 5 is 3 remainder 2. // gives the 3 and % gives the 2. The remainder is handy for checking things like "is this number even?": a number is even when number % 2 is 0.
Negative numbers and absolute value
print(-8 + 3)
print(-4 * -5)
print(abs(-12))
-5
20
12
abs gives the absolute value: the distance from zero, ignoring the minus sign. It's used to measure the size of an error, whichever direction it's in.
Variables: give numbers a name
A variable stores a value under a name, like a labelled box:
price = 1200
discount = 0.15 # 15%
saving = price * discount
final_price = price - saving
print(saving, final_price)
180.0 1020.0
This is the same idea as letters in algebra: price plays the role of x. Variable names can't contain spaces, so use underscores, as in final_price.
Rounding
average = 1000 / 3
print(average)
print(round(average, 2)) # 2 decimal places
print(round(average)) # nearest whole number
print(f"{average:.1f}") # 1 decimal place, for display
333.3333333333333
333.33
333
333.3
round(number, digits) rounds a number. The last line is an f-string, which formats a number for display without changing it; Python f-strings explains them.
One surprise: round(2.5) gives 2 and round(3.5) gives 4. Python rounds exact halves to the nearest even number, which avoids a bias towards rounding up over many calculations.
The math module
For more advanced maths, load the built-in math module with import:
import math
print(math.sqrt(16)) # square root
print(math.pi) # π
print(math.e) # Euler's number e
print(math.exp(1)) # e to the power 1
print(math.log(100, 10)) # log of 100 in base 10
print(math.floor(4.7), math.ceil(4.2))
4.0
3.141592653589793
2.718281828459045
2.718281828459045
2.0
4 5
math.sqrtis a clearer way to write a square root than** 0.5.math.log(100, 10)asks "10 to what power gives 100?", and the answer is 2. Logarithms have their own lessons later in this course.floorrounds down andceilrounds up.
Exact fractions
Decimals can't represent ⅓ exactly. Python's fractions module can:
from fractions import Fraction
a = Fraction(1, 3)
b = Fraction(1, 6)
print(a + b)
print(Fraction(3, 4) * 2)
print(float(Fraction(3, 8)))
1/2
3/2
0.375
⅓ + ⅙ = ½, exactly as you'd work out by hand. float() converts a fraction to a decimal. This is great for checking your fraction homework in the numbers module.
Working with lists of numbers
This is where Python leaves a calculator behind. A list holds many numbers, and built-in functions summarise them in one line:
scores = [72, 85, 90, 64, 85]
print(len(scores)) # how many
print(sum(scores)) # total
print(min(scores), max(scores)) # smallest, largest
print(sum(scores) / len(scores)) # the mean (average)
print(sorted(scores)) # in order
5
396
64 90
79.2
[64, 72, 85, 85, 90]
The mean is the total divided by how many: 396 ÷ 5 = 79.2. You've just done your first piece of statistics, and the Statistics course builds on exactly this.
Do maths on every number at once with NumPy
NumPy is the library data scientists use for maths on lists of numbers. It applies an operation to every value at once:
import numpy as np
prices = np.array([100, 250, 80, 400])
print(prices * 1.18) # add 18% tax to every price
print(prices.mean()) # the average
print(np.sqrt(prices)) # square root of each
[118. 295. 94.4 472. ]
207.5
[10. 15.8113883 8.94427191 20. ]
prices * 1.18 multiplies every price by 1.18 in one go, with no loop. NumPy prints decimals in neat columns, which is why you see 118. instead of 118.0.
NumPy comes with most Python data science setups; if it's missing, see the NumPy array tutorial.
Practice
- A phone costs ₹18,000. It's on sale at 12% off. Use Python to find the sale price.
Show the answer
price = 18000
print(price - price * 0.12)
It costs ₹15,840. price * 0.88 gives the same answer in one step.
- Predict, then check: what does
2 + 3 ** 2 * 2give?
Show the answer
Powers first: 3 ** 2 is 9. Then multiply: 9 * 2 is 18. Then add: 2 + 18 = 20.
- Find the average of these temperatures: 31, 29, 35, 33, 30.
Show the answer
temps = [31, 29, 35, 33, 30]
print(sum(temps) / len(temps))
The total is 158, and 158 / 5 = 31.6.
- Use
Fractionto calculate ¾ − ⅖.
Show the answer
from fractions import Fraction
print(Fraction(3, 4) - Fraction(2, 5))
The answer is 7/20.
Key takeaways
- Python's operators:
+ - * /for arithmetic,**for powers,//and%for whole-number division and remainders. - Python follows the usual order of operations; add brackets whenever in doubt.
- Variables store values with names, like letters in algebra.
- The
mathmodule adds square roots, π, e, logs and rounding;fractionsgives exact fractions. - Lists and NumPy let you calculate with many numbers at once, which is what data science is all about.
- Predict the output before you run code: it's the fastest way to learn.
Frequently asked questions
Why does Python give 0.30000000000000004 for 0.1 + 0.2?
Computers store decimals in binary, and numbers like 0.1 can't be stored exactly, so tiny errors appear in the last digits. Round the result for display, or use math.isclose to compare decimals.
Is Python better than a calculator for learning maths?
For data science, yes. Python stores values, handles whole lists of numbers, shows every step, and the same code then works on real datasets with thousands of rows.
What is the difference between / and // in Python?
/ is normal division and always gives a decimal, so 7 / 2 is 3.5. // is floor division and gives the whole-number part, so 7 // 2 is 3.
What to learn next
- Go back to maths for data science from zero for the full learning path.
- Practise your Python basics in Python numbers and operators.