Tutorials / Python from Scratch / Numbers and arithmetic

Numbers and arithmetic

12 min read python
Course contents (15 lessons)
  1. Getting started
  2. Installing Python 3.13 and running your first script
  3. Variables and basic data types
  4. Text, numbers and user input
  5. Working with strings
  6. Numbers and arithmetic
  7. Input and output: talking to the user
  8. Making decisions and repeating work
  9. Making decisions with if, elif and else
  10. Loops: for, while, break and continue
  11. Collections of data
  12. Lists and tuples
  13. Dictionaries and sets
  14. Functions and modules
  15. Writing your own functions
  16. Modules, pip and virtual environments
  17. Files and errors
  18. Reading and writing files
  19. Errors and exceptions
  20. Final project: expense tracker
  21. Project: build the expense tracker, part 1
  22. Project: summaries, search and improvements

Python is a good calculator

Open the REPL and try some sums. You will use these operators more than any others in your first year of programming.

OperatorMeaningExampleResult
+Add7 + 29
-Subtract7 - 25
*Multiply7 * 214
/Divide (always a float)7 / 23.5
//Floor division7 // 23
%Remainder (modulo)7 % 21
**Power7 ** 249

Two kinds of division

The single slash always gives a float, even when the answer is whole: 10 / 2 is 5.0. Double slash throws away the fraction and gives a whole number. It rounds down, so -7 // 2 is -4, not -3. That surprises people who come from other languages.

The modulo operator % gives the remainder. It sounds like a maths-class idea, but it is useful. It tells you whether a number is even (n % 2 == 0), and it lets you turn a total of minutes into hours and minutes.

total_minutes = 275

hours = total_minutes // 60
minutes = total_minutes % 60
print(f"{total_minutes} minutes = {hours} h {minutes} min")

# A simple bill with tax
subtotal = 2480
tax_rate = 0.17
tax = subtotal * tax_rate
total = subtotal + tax
print(f"Subtotal: {subtotal}")
print(f"Tax: {tax:.2f}")
print(f"Total: {total:.2f}")

# Dividing a bill between friends
bill = 3000
people = 7
share = bill / people
print(f"Each person pays {share:.2f}")
print(f"Whole rupees only: {bill // people}, left over: {bill % people}")

Output:

275 minutes = 4 h 35 min
Subtotal: 2480
Tax: 421.60
Total: 2901.60
Each person pays 428.57
Whole rupees only: 428, left over: 4

Order of operations

Python follows the same order as school maths: brackets first, then powers, then multiplication and division, then addition and subtraction. So 2 + 3 * 4 is 14. When in doubt, add brackets. They cost nothing and they make your intention clear: (2 + 3) * 4 is 20.

Shortcut operators

You often update a variable using its own value. Python has short forms.

stock = 50
stock -= 5     # same as stock = stock - 5
stock += 20    # now 65
stock *= 2     # now 130
print(stock)

Python has no ++ operator. Use stock += 1.

Rounding

The round() function rounds a number. round(3.14159, 2) gives 3.14. Be careful with halves. Python rounds to the nearest even number, so round(2.5) is 2 and round(3.5) is 4. This is called banker's rounding. For display, an f-string with :.2f is usually what you want.

Floats are not exact

Try this in the REPL:

>>> 0.1 + 0.2
0.30000000000000004
>>> 0.1 + 0.2 == 0.3
False

This is not a Python bug. Computers store floats in binary, and some decimal fractions cannot be written exactly in binary, just like 1/3 cannot be written exactly in decimal. For quick calculations it does not matter. For money, it can. The standard library has a decimal module that does exact decimal arithmetic. To compare floats, use math.isclose(a, b) instead of ==.

Useful built-ins and the math module

Python gives you abs(), min(), max(), sum() and round() without any setup. For more, import the math module:

import math

print(math.sqrt(144))     # 12.0
print(math.ceil(4.2))     # 5
print(math.floor(4.8))    # 4
print(math.pi)            # 3.141592653589793

Large numbers and underscores

Integers in Python have no fixed size limit. 2 ** 200 works fine. For readability you can write 1_000_000 with underscores. Python ignores them.

Try it yourself

Write a script that has a price of 1999 rupees and a discount of 15 percent. Print the discount amount and the final price with two decimals. Then convert 5000 seconds into hours, minutes and seconds using // and %. The answer is 1 hour, 23 minutes and 20 seconds.

python
total_minutes = 275

hours = total_minutes // 60
minutes = total_minutes % 60
print(f"{total_minutes} minutes = {hours} h {minutes} min")

# A simple bill with tax
subtotal = 2480
tax_rate = 0.17
tax = subtotal * tax_rate
total = subtotal + tax
print(f"Subtotal: {subtotal}")
print(f"Tax: {tax:.2f}")
print(f"Total: {total:.2f}")

# Dividing a bill between friends
bill = 3000
people = 7
share = bill / people
print(f"Each person pays {share:.2f}")
print(f"Whole rupees only: {bill // people}, left over: {bill % people}")

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account