Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pyschool is wrong ?

Tags:

python

I'm currently learning python and trying to do exercises at pyschools (if anyone knows what it is). Anyway, i have an exercise that asks me to do the following : Write a function percent(value, total) that takes in two numbers as arguments, and returns the percentage value as an integer.

Here's my code:

def percent(value, total):
    percent = value / total * 100
    return int(percent)

It works great in my Python Idle and it gives all the correct answers. however, when i run it in the pyschools website, it says that , for example , when the function is called with parameters 46 and 90 , the function returns 0. However, in my python idle , it correctly returns 51. What might be the problem ? Thank you very much for your help!

like image 223
stensootla Avatar asked Mar 19 '26 21:03

stensootla


2 Answers

You need to use float division.

In your case you can apply this little trick:

percent = (100. * value) / total

when one of the factors is a float the operations give you floats. You do not need to convert all. Note this does not work:

percent = (value / total) * 100.

because the first operation is performed in integer mode

(btw don't forget to convert percent to integer to fit the requirements of the school. I didnt do it for clarity)

like image 184
joaquin Avatar answered Mar 21 '26 10:03

joaquin


In python 2.x, division is integer division, in python 3.x, it's not. This probably explains your issue.

Also, you could be using brackets to make your code more readable.

like image 36
Thomas Orozco Avatar answered Mar 21 '26 10:03

Thomas Orozco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!