Numbers and arithmetic
Course contents (15 lessons)
- Getting started
- Installing Python 3.13 and running your first script
- Variables and basic data types
- Text, numbers and user input
- Working with strings
- Numbers and arithmetic
- Input and output: talking to the user
- Making decisions and repeating work
- Making decisions with if, elif and else
- Loops: for, while, break and continue
- Collections of data
- Lists and tuples
- Dictionaries and sets
- Functions and modules
- Writing your own functions
- Modules, pip and virtual environments
- Files and errors
- Reading and writing files
- Errors and exceptions
- Final project: expense tracker
- Project: build the expense tracker, part 1
- 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.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Add | 7 + 2 | 9 |
- | Subtract | 7 - 2 | 5 |
* | Multiply | 7 * 2 | 14 |
/ | Divide (always a float) | 7 / 2 | 3.5 |
// | Floor division | 7 // 2 | 3 |
% | Remainder (modulo) | 7 % 2 | 1 |
** | Power | 7 ** 2 | 49 |
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.
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