Puzzle 18 Round and Round We Go
Python Brain Teasers — by Miki Tebeka (27 / 40)
👈 Endgame | TOC | TF (Without IDF) 👉
print(round(1.5), round(2.5))
Guess the Output
IMPORTANT
Try to guess what the output is before moving to the next page.
This code will print: 2 2
Rounding seems easy. round(1.1) evaluates to 1. round(1.8) evaluates to 2. The question is, how do you round the .5 numbers? Should you round up? Down? Turns out, there are a lot of ways to do it.
Python 3 uses bankers’ rounding. Odd numbers are rounded up; even numbers are rounded down. The reasoning behind this method is that if you round a list of numbers, assuming there’s roughly the same number of odd and even numbers, the error (rounding) will cancel each other.
Python 2 uses a different method called round away from zero. If you run this teaser in Python 2, you’ll see (2.0, 3.0) as the output.