Why does Python return 0 for simple division calculation?

Python

Python Problem Overview


Why does this simple calculation return 0

>>> 25/100*50  
0

while this actually calculates correctly?

>>> .25*50
12.5

>>> 10/2*2  
10

What is wrong with the first example?

Python Solutions


Solution 1 - Python

In Python 2, 25/100 is zero when performing an integer divison. since the result is less than 1.

You can "fix" this by adding from __future__ import division to your script. This will always perform a float division when using the / operator and use // for integer division.

Another option would be making at least one of the operands a float, e.g. 25.0/100.

In Python 3, 25/100 is always 0.25.

Solution 2 - Python

This is a problem of integer truncation (i.e., any fractional parts of a number are discarded). So:

25 / 100 gives 0

However, as long as at least one of the operands in the division is a float, you'll get a float result:

 25 / 100.0 or 25.0 / 100  or 25.0 / 100.0 all give 0.25

Solution 3 - Python

25/100 is an integer calculation which rounds (by truncation) to 0.

Solution 4 - Python

I solved this problem just by doing this trick. > (25 * 1.0) / 100 * 50

So, (1.0) makes sure that the numerator be float type

Solution 5 - Python

Python 2 returns zero for integer division if result is less than 1.

Solution is to convert one of the integers to float e.g.

float(25)/100*50

Solution 6 - Python

  • In Python 2: 25/100 is an integer division by default

  • In Python 3: 25/100 is always 0.25.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfenerlitkView Question on Stackoverflow
Solution 1 - PythonThiefMasterView Answer on Stackoverflow
Solution 2 - PythonLevonView Answer on Stackoverflow
Solution 3 - PythonMarcinView Answer on Stackoverflow
Solution 4 - PythonEfrainView Answer on Stackoverflow
Solution 5 - PythonNdhetiView Answer on Stackoverflow
Solution 6 - PythonjavaseView Answer on Stackoverflow