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!
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With