Numbers and their operators
Worked examples
Read the claim, then run it and check the machine agrees. One at a time — nothing here is taken on trust.
print("7 / 2 :", 7 / 2) # true division -> always a float
print("10 / 5 :", 10 / 5) # even split, STILL a float: 2.0
print("7 // 2 :", 7 // 2) # floor division -> int quotient
print("7 % 2 :", 7 % 2) # modulo -> the remainder
print("2 ** 10 :", 2 ** 10) # power
print("2 ** 0.5:", 2 ** 0.5) # a fractional power is a root
print("type(4 / 2) :", type(4 / 2).__name__) # float
print("type(4 // 2):", type(4 // 2).__name__) # int
Read the two type lines carefully. 4 / 2 and 4 // 2 are both "two",
but / hands back the float 2.0 while // hands back the int 2.
The operator, not the numbers, decides the type of the answer.
a, b = -7, 3
print("a // b :", a // b) # -3, floored toward -infinity
print("a % b :", a % b) # 2, sign follows the divisor
print("rebuilt:", (a // b) * b + (a % b)) # back to a?
print("holds? :", a == (a // b) * b + (a % b))
print("truncation would give:", -3, "but // gives", -7 // 2)
-7 // 3 floors to -3 (not -2), and -7 % 3 is 2 (not -1), and
the two fit together perfectly: (-3) * 3 + 2 is -7, so the identity
a == (a // b) * b + (a % b) still holds. The last line contrasts
flooring with truncation: -7 // 2 is -4, while chopping toward zero
would have said -3.
growth = 1000 * 1.05 ** 3
print("1000 * 1.05 ** 3 =", growth)
print("clean paper answer would be 1157.625")
The result is 1157.6250000000002, not the tidy 1157.625 you would
get on paper. Nothing is wrong with the code — 1.05 cannot be stored
exactly in binary, so a microscopic error rides along. This is normal,
expected float behaviour, and now you will recognise it on sight.
Check the concept
One question at a time. Unsure? Revisit the lecture, then answer.
The challenge
Pass the quiz to unlock the challenge — your code will still be waiting here.