Why does dividing two integers produce a float in Python?
Asked by
bead loom
I'm trying to understand why an expression like 100 / 25 evaluates to 4.0 instead of 4 when both operands are integers. Is this intentional, and what should I use when I specifically want an integer result?
Answers
This behavior is different from older Python versions, where dividing two integers could produce integer division. In modern Python, / is consistently true division, and // explicitly requests an integer-style result.
Reply to this answer
In Python, the / operator always performs regular division and returns a floating-point result, even when the answer is a whole number. This keeps the result type predictable and also handles cases like 1 / 2, which should be 0.5 rather than an integer.
Reply to this answer
Use // when you want floor division: 100 // 25 gives 4, while 40 // 3 gives 13. Keep in mind that // rounds down, so for negative values it may differ from simply truncating toward zero.
Reply to this answer
The language is choosing mathematical division rather than basing the result solely on the input types. If the exact result is 4, Python still represents it as 4.0 because the same operator must also support non-whole results such as 100 / 30.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions