Data Types and Operations
In these exercises, you will use integers for whole numbers such as 7, and floats for numbers such as 3.75. Arithmetic operators combine these values.
Arithmetic operators
+add,-subtract,*multiply/divide — for integers and floats, gives a float (10 / 2is5.0)//floor division — divide and round the result down toward negative infinity. For example,7 // 2is3, while-7 // 2is-4.%modulo — the remainder left over (7 % 2is1)**power (2 ** 3is8)
print("10 + 3 =", 10 + 3)
print("10 / 3 =", 10 / 3)
print("10 // 3 =", 10 // 3)
print("10 % 3 =", 10 % 3)
print("2 ** 3 =", 2 ** 3)
Each line shows the operator and the answer it produces.
Dividing integers and floats
With the integer and float values used here, / returns a float even when the division is exact. For example, 6 / 3 produces 2.0.
Rounding
round(value, n) returns a number rounded to n decimal places. It does not control how many trailing zeroes are displayed. For example, round(2.0, 2) still displays as 2.0 when printed normally.
average = 37 / 3
print(average)
print(round(average, 2))
Order of operations
Python follows normal maths order — * and / happen before + and -.
Use parentheses when you want a different order:
print(2 + 3 * 4)
print((2 + 3) * 4)
See also: Variables.
Your turn
Add two lines: print a floor-divided by b, then print the remainder of
a divided by b.
a = 17
b = 5
# add two prints: floor division first, then the remainder
Expected output
3
2
Practise this in the free Python course, where every exercise checks your code instantly.