While Statement

Andre Engels andreengels at gmail.com
Fri May 22 11:34:18 CEST 2009


On Fri, May 22, 2009 at 11:17 AM, Joel Ross <joelc at cognyx.com> wrote:
> Hi all,
>
> I have this piece of code
>
> class progess():
>
>    def __init__(self, number,  char):
>
>        total = number
>        percentage = number
>        while percentage > 0 :
>            percentage = int(number/total*100)
>            number-=1
>            char+="*"
>            print char
>
> progess(999,  "*")
>
> Just wondering if anyone has any ideas on way the percentage var gets set to
> the value 0 after the first loop.
>
> Any feed back would be appreciated.

In Python 2.6 and lower, division of two integers gives an integer,
being the result without rest of division with rest:

>>> 4/3
1
>>> 5/3
1
>>> 6/3
2
>>>

In your example, the second run has number = 998, total = 999. 998/999
is evaluated to be zero.

There are two ways to change this:
1. Ensure that at least one of the things you are using in the
division is a float. You could for example replace "total = number" by
"total = float(number)" or "number/total*100" by
"float(number)/total*100" or by "(number*100.0)/total".
2. Use Python 3 behaviour here, which is done by putting the import
"from __future__ import division" in your code.


-- 
André Engels, andreengels at gmail.com



More information about the Python-list mailing list