Why does percentage calculation only work one way around?

Hello everyone!

I wondered why this works to calcualte a percentage:

percentage_ceballos = 100 * total_ceballos/len(survey_responses)

but this not:

percentage_ceballos = total_ceballos/len(survey_responses) * 100

and neither this:

percentage_ceballos = 100/len(survey_responses) * total_ceballos

The task is Nr. 3 in the last numpy project. but that doesn’t seem too important.

Strangely, my school way of notation doesn’t work and I wondered why! Any idea?

1 Like

Looks like some of the fun you can have with Python 2. The issue is that division between two integers always gives you an integer in Python2.

So in this example with 70 survey responses and 33 ‘Ceballos’ that division on it’s own…
33 / 70 == 0 in Python 2 (equates to zero).

So we know why things go a bit wrong. But why is this not consistent? Operator precedence doesn’t go in the order you may be used to from mathematics. In fact a number of things are grouped together and for items with the same order of precedence they are grouped left to right. See the docs for details-
Python2-operator precedence

So for the one that works…

percentage_ceballos = 100 * total_ceballos / len(survey_responses)
# actually cacluates like this in typical math...
percentage_ceballos = (100 * total_ceballos) / len(survey_responses)

So what we have instead is 3300 / 70. In Python 2 this equates to 47 and the decimal places are ignored. The others however have multiplication of zero or something along those lines which is changing your results.

So it’s a mix of Python2 integer division and what may be an unexpected order of operations for you.

If you wanted to avoid this make sure one of the numbers is a float e.g. (3 / float(4)) or consider importing division from __futures__ but be aware that changes all division.

1 Like

so the solution is to convert at least one integer to a float, of course. At least in Python 2.

Thank you for your helpful answer!