【问题标题】:Python, first time using Decimal and quantizePython,第一次使用 Decimal 和 quantize
【发布时间】:2013-01-12 04:40:24
【问题描述】:

我只是想知道是否有人对如何改进此代码有任何意见。我的目标是让它尽可能像 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!"

【问题讨论】:

  • 我认为你的程序需要一些异常处理来处理非法输入
  • 更适合 codereview.sx?
  • @nneonneo 是的,它可能更适合 codereview.sx,但我想,因为我是新手,所以可能会出现一些严重的错误,可能会带来更有趣的方法事物。但你可能是对的。

标签: python string dictionary decimal


【解决方案1】:
  1. 将产品字典称为“产品”或类似的描述性名称,而不仅仅是“字典”
  2. 一般来说,如果您在一个范围内进行迭代,请使用 xrange 而不是 range 以获得更好的性能(尽管在这样的应用中这是一个非常小的挑剔)
  3. 您可以使用subtotal = sum(dictionary.itervalues()) 快速将所有商品价格相加,而无需使用循环。
  4. 您绝对应该在整个过程中使用 Decimal 以避免由于float 而导致的不准确。
  5. 您可以使用诸如'%.2f' % value(旧式格式)或'{:.2f}' .format(value)(新式格式)之类的格式字符串来打印带两位小数的值。
  6. 税值应该是一个常数,因此可以很容易地更改(它在两个地方使用,一次用于计算,一次用于显示)。

【讨论】:

    【解决方案2】:
    • 更新字典,我会使用dict[key] = value,而不是dict.update({key:value})

    • 尝试使用格式规范,而不是连接字符串。这看起来更简洁,并且无需将值显式转换为字符串。

      • C 风格:"Qty: %d, Price: %f" % (qty, price)
      • 字符串格式:"Qty: {0}, Price {1}".format(qty, price)

    【讨论】:

    • 感谢您的意见。我实际上使用了 dict.update,因为我在堆栈溢出的某个地方发现有人说使用它比使用 dict[key] = value 更好。你有理由喜欢一个而不是另一个吗?对方也没有真正的理由,他们只是说他们就是这么做的。
    • 说实话,主要原因很简单,我一直都是这样。我还认为它读起来更清楚,并直接映射到您从字典中检索值的方式:dict[key] = value -> value = dict[key]dict.update() 主要用于组合多个字典。
    【解决方案3】:

    1 在字典中添加键值,您可以使用:

    dictionary[currentProduct] = currentPrice
    

    但是,在这种情况下,您不需要 dict,因为 dict 是无序的。您可以使用元组列表。

    2 为什么不使用Decimal(raw_input()),那么你可以在不使用浮点数的情况下进行所有十进制计算。

    3 打印结果,不需要先将值转换为str,可以使用str.format()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-11
      • 2017-07-10
      • 2011-11-09
      • 1970-01-01
      • 2010-11-29
      • 1970-01-01
      • 2017-03-30
      相关资源
      最近更新 更多