首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python,首次使用Decimal和quantize

Python,首次使用Decimal和quantize
EN

Stack Overflow用户
提问于 2013-01-12 12:40:25
回答 3查看 1.8K关注 0票数 1

我只是想知道是否有人对如何改进这段代码有什么建议。我的目标是让它尽可能的具有python风格,因为我正在努力学好python。这个程序运行得很好,但是如果你看到任何你认为可以改进的东西(不是主要的变化,只是基本的“我是python新手”之类的东西),这个程序请让我知道。

代码语言:javascript
复制
#!/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!"
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-01-12 13:31:50

  1. 将产品字典称为"products“或一些类似的描述性名称,如果您正在迭代某个范围,请使用xrange而不是range以获得更好的性能(尽管在这样的应用程序中这是一个非常小的吹毛求疵)
  2. 您可以使用subtotal = sum(dictionary.itervalues())快速将所有项目的价格相加。float.
  3. You可以使用诸如'%.2f' % value (旧式格式)或'{:.2f}' .format(value) (新式格式)这样的格式字符串来打印带有两个小数位的值。
  4. 税值应该是一个常量,因此可以很容易地进行更改(它用于两个位置,一次用于计算,一次用于显示)。
票数 3
EN

Stack Overflow用户

发布于 2013-01-12 12:54:43

在更新字典时,我会使用dict.update({key:value})

  • Instead而不是
  • 来连接字符串,尝试使用dict[key] = value规范。这样看起来更整洁,使您不必显式地将值转换为字符串。

代码语言:javascript
复制
- C-style: `"Qty: %d, Price: %f" % (qty, price)`
- string.format: `"Qty: {0}, Price {1}".format(qty, price)`

票数 1
EN

Stack Overflow用户

发布于 2013-01-12 13:00:26

1要在dict中添加key-value,可以使用:

代码语言:javascript
复制
dictionary[currentProduct] = currentPrice

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

2为什么不使用Decimal(raw_input()),这样你就可以不用浮点数就可以用十进制来完成所有的计算。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14290300

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档