Numbers and operators
Basics8 min readLesson 3 of 8
Python stores whole numbers as integers (int) and decimal numbers as floats (float). The usual operators are +, -, *, and /, with // for floor division, % for the remainder, and ** for powers. Bills, marks, averages, and measurements all depend on these rules.
whole = 17
part = 5
print(whole + part)
print(whole // part)
print(whole % part)Output
22 3 2
3.1 Order of operations
Arithmetic follows the order you learned in school:
- Powers
- Multiplication and division
- Addition and subtraction
Parentheses let you state the order yourself, so (2 + 3) * 4 runs the addition first.
3.2 Division and types
/always returns a float, even when the numbers divide evenly:8 / 2gives4.0.//returns how many whole groups fit, rounded down.%returns what is left.- Mixing an
intand afloatproduces afloat.
A total built from a price with paise can come back with a decimal part for that reason.
print(2 + 3 * 4)
print((2 + 3) * 4)
print(8 / 2)
print(8 // 3)
print(8 % 3)Output
14 20 4.0 2 2
3.3 Common mistake
Expecting / to return a whole number leads to confusing output. Using // when a decimal average is needed has the opposite problem. For example, 7 // 2 is 3, while 7 / 2 is 3.5, so choose the operator that matches the question. When a calculation mixes several operators, add parentheses around the part you want first. Use round(value, 2) when a result should be rounded to two decimal places.
price = 19.99
quantity = 3
total = price * quantity
print(type(total))
print(round(total, 2))Output
<class 'float'> 59.97
3.4 Practice
- Write a bill for three items with an integer price for each.
- Print the subtotal, the tax at 5 percent, and the final total.
- Round the final total with
round(final_total, 2).
Repeat the calculation with one price stored as a float and check whether the printed type changes.
