It Doesn't Add Up!

Stephen Hansen apt.shansen at gmail.com
Mon Oct 12 20:46:33 CEST 2009


On Mon, Oct 12, 2009 at 11:33 AM, Victor Subervi <victorsubervi at gmail.com>wrote:

>     for row in data:
>       i += 1
>       total = 0
>       quantity = form.getfirst('order_' + str(i), '')
>       if quantity != '':
>         sql = 'select * from products p join %s c on p.ID=c.ID where
> c.ID=%s;' % (client, str(i))
>         cursor.execute(sql)
>         stuff = cursor.fetchone()
>         price = str(int(stuff[5]*100))
>         price = price[0:len(price)-2] + '.' + price[-2:]
>         item, price, description, discount = stuff[2], price, stuff[3],
> stuff[8]
>         order += 'Item #: ' + item + '\tQuantity: ' + quantity + '\tPrice:
> ' + price + '\tDiscount: ' + str(discount) + '\tDescription: ' +
> description[:20] + '...<br />\n'
>         print 'Total 1: %s<br />' % total
>         total += float(price) * int(quantity) * (100 - discount)/100
>         print 'Total 2: %s<br />' % total
>       order += 'TOTAL: $' + str(total)
>
>
First, consider using the "decimal" module and not floats for money, so you
don't get weird rounding. Floats are inexact. People usually prefer money to
be exact.

Second, you initialize "total" to 0, and before "Total 1" is printed out--
you're never changing it unless I'm blind. You change it the first time
below "Total 1".

Finally, consider being explicit with the "SELECT <columns> FROM <table>"
and not using *. It lets you semi-future-proof your code verses future table
changes, and is easier to maintain as you see in the code what order things
come out and don't have to remember the order in the table itself.

HTH,

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091012/9b3b4d95/attachment.html>


More information about the Python-list mailing list