我只是想知道是否有人对如何改进这段代码有什么建议。我的目标是让它尽可能的具有python风格,因为我正在努力学好python。这个程序运行得很好,但是如果你看到任何你认为可以改进的东西(不是主要的变化,只是基本的“我是python新手”之类的东西),这个程序请让我知道。
#!/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!"发布于 2013-01-12 13:31:50
xrange而不是range以获得更好的性能(尽管在这样的应用程序中这是一个非常小的吹毛求疵)subtotal = sum(dictionary.itervalues())快速将所有项目的价格相加。float.'%.2f' % value (旧式格式)或'{:.2f}' .format(value) (新式格式)这样的格式字符串来打印带有两个小数位的值。发布于 2013-01-12 12:54:43
在更新字典时,我会使用dict.update({key:value})
dict[key] = value规范。这样看起来更整洁,使您不必显式地将值转换为字符串。- C-style: `"Qty: %d, Price: %f" % (qty, price)`
- string.format: `"Qty: {0}, Price {1}".format(qty, price)`
发布于 2013-01-12 13:00:26
1要在dict中添加key-value,可以使用:
dictionary[currentProduct] = currentPrice但是,在这种情况下,您不需要dict,因为dict是无序的。您可以使用元组列表。
2为什么不使用Decimal(raw_input()),这样你就可以不用浮点数就可以用十进制来完成所有的计算。
3要打印结果,不需要先将值转换为字符串,您可以使用str.format()
https://stackoverflow.com/questions/14290300
复制相似问题