Why does this code keep printing out 0? Election Results

https://www.codecademy.com/courses/intro-statistics-numpy/projects/election-binomial
Whenever I try to write this code for number 3:

percentage_ceballos = total_ceballos/len(survey_responses)

It prints out 0 and I can’t understand why.
Then when I put 100 * in front of it:

percentage_ceballos =100 * total_ceballos/len(survey_responses)

It prints out 47, the desired answer.
Similarly, the answer is this:

percentage_ceballos = total_ceballos/float(len(survey_responses))

Why does that fix the problem as well?

That sounds like Python2 to me where integer division performs floor division. As you noted making one of the values in your expression into a float sorted the issue. *Bounced this into get help-python.

2 Likes

The 100 * is there to convert the decimal (0.47) to a percentage (47%).

As for the division, that’s strange. As @tgrtim mentioned, it’s what would have happened in Python 2.

Was this course made for Python 2? Because I really don’t get this. I learned Python 3. Also, I’m 99% sure that in Python 3, even if you don’t put the 100* it will give you 0.47.

That particular project would appear to be using Python 2, yes:

That would seem to explain the floor division behaviour. :sweat:

2 Likes

Is there a particular reason why it’s using Python 2?

It’s older content. The pro content is all python 3 I think.

I think it’s just a bit inconsistent with versioning throughout and sometimes you’ll have to test which version is actually running, e.g. import sys; print(sys.version). If it really bothers you, you could always import the relevant bits: from __future__ import division and such though you’d need to copy it into each script so sometimes it’ll just be easier with float().

Yep, this is an older project. It was part of the Data Analytics Intensive that I took in 2017.

1 Like