When I started to learn Python 3, I used to be confused about the semantics of dividing two integers. Is the result a float or an integer value?
The reason for my confusion was a nasty Java bug that I once found in my code. The code was supposed to perform a simple division of two integers to return a parameter value between zero and one. But Java uses integer division, i.e., it skips the remainder. Thus, the value was always either zero or one, but nothing in-between. It took me days to figure that out.
Save yourself the debugging time by memorizing the following rule once and for all.
// operator performs integer division and the single-backslash
/ operator performs float division. An example for integer division is
40//11 = 3. An example for float division is
40/11 = 3.6363636363636362.
How Does Integer Division Work In Python?
Integer division consists of two steps:
- Perform normal float division
a / b.
- Round the resulting float number down to the next integer.
Here’s an example:
x = 30 // 11 print(x) # 2
Interactive Shell + Puzzle
You can try it in our interactive Python shell:
Exercise: What is the output of this code snippet?
Although the puzzle seems simple, more than twenty percent of the Finxter users cannot solve it. You can check whether you solved it correctly here: Test your skills now!
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.