Reputation: 2270
I was just wondering if anybody had any input on how to improve this code. My goal is for it to be as pythonic as possible since I'm trying to really learn python well. This program works fine, but if you see anything that you think could be done to improve (not major changes, just basic "Im new to python" stuff) this program please let me know.
#!/usr/bin/python
from decimal import *
print "Welcome to the checkout counter! How many items are you purchasing today?"
numOfItems = int(raw_input())
dictionary = {}
for counter in range(numOfItems):
print "Please enter the name of product", counter + 1
currentProduct = raw_input()
print "And how much does", currentProduct, "cost?"
currentPrice = float(raw_input())
dictionary.update({currentProduct:currentPrice})
print "Your order was:"
subtotal = 0
for key, value in dictionary.iteritems():
subtotal = subtotal + value
stringValue = str(value)
print key, "$" + stringValue
tax = subtotal * .09
total = subtotal + tax
total = Decimal(str(total)).quantize(Decimal('0.01'), rounding = ROUND_DOWN)
stringSubtotal = str(subtotal)
stringTotal = str(total)
print "Your subtotal comes to", "$" + stringSubtotal + ".", " With 9% sales tax, your total is $" + stringTotal + "."
print "Please enter cash amount:"
cash = Decimal(raw_input()).quantize(Decimal('0.01'))
change = cash - total
stringChange = str(change)
print "I owe you back", "$" + stringChange
print "Thank you for shopping with us!"
Upvotes: 1
Views: 1945
Reputation: 179422
xrange
instead of range
for better performance (though it's a very minor nitpick in an app like this)subtotal = sum(dictionary.itervalues())
to quickly add up all the item prices, without having to use the loop.float
.'%.2f' % value
(old-style format) or '{:.2f}' .format(value)
(new-style format) to print out values with two decimal places.Upvotes: 3
Reputation: 97291
1 to add key-value in a dict, you can use:
dictionary[currentProduct] = currentPrice
but, you don't need a dict in this case, because dict is orderless. You can use a list of tuple.
2 Why not use Decimal(raw_input())
, then you can do all the calculation in decimal without using floats.
3 To print the result, you don't need convert values to str first, you can use str.format()
Upvotes: 1
Reputation: 704
Updating a dictionary, I would use dict[key] = value
, rather than dict.update({key:value})
Instead of concatenating strings, try using format specification. This looks cleaner and saves you having to convert values to strings explicitly.
"Qty: %d, Price: %f" % (qty, price)
"Qty: {0}, Price {1}".format(qty, price)
Upvotes: 1