Puzzle 18 Round and Round We Go

The Pragmatic Programmers
The Pragmatic Programmers
2 min readMar 23, 2022

--

Python Brain Teasers — by Miki Tebeka (27 / 40)

👈 Endgame | TOC | TF (Without IDF) 👉

round.py

​ ​print​(round(1.5), round(2.5))

Guess the Output

IMPORTANT

Try to guess what the output is before moving to the next page.

images/hline.png

This code will print: 2 2

images/hline.png

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.

Further Reading

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.