帮助使用python cod

2024-05-14 23:20:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在阅读这本名为“软件设计的python”的python书籍,它有以下练习:

Suppose the cover price of a book is $24.95, but the bookstores get a 40% discount. Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies

好的,我有以下代码:

bookPrice = 24.95
discount = .60
shippingPriceRest = .75
shippingPriceFirst = 3.00
totalUnits = 60

bookDiscountAmount = bookPrice * discount * totalUnits
shipping = shippingPriceRest * 59 + shippingPriceFirst

result = bookDiscountAmount + shipping


print 'The total price for 60 books including shipping and discount is: '
print 'Total price of the books is: ' + str(bookDiscountAmount)
print 'Total Shipping is: ' + str(shipping)
print 'The Total price is: ' + str(result)

我得到了以下结果:

  • 包括运费和折扣在内的60本书的总价为:
  • 这些书的总价是:898.2英镑
  • 总运费为:47.25
  • 总价为:945.45

  • 我的问题是:

    • 是这样吗?
    • 我怎样才能使代码更好?

Tags: andoftheforisdiscountpricetotal
3条回答

在我看来是对的。我会避免硬编码59。取而代之的是,检查总数是否超过一个,并根据需要进行划分。

而且,这是次要的,但是bookDiscountAmount应该是bookDiscountedAmount(折扣是他们节省的金额,而不是他们支付的金额)。其他人已经指出如何改进字符串打印。

只有三件事需要改变:

1)您复制了图书数量:60本和59本都出现在代码中。你不应该有59个在里面。

2)按如下方式打印结果:print 'The total price is: %.2f' % result

3)通常的Python约定是像这样命名变量,而不是像这样命名。

我建议的唯一改进是使用format-函数而不是字符串连接:

print """The total price for {0:d} books including shipping and discount is: 
         Total price of the books is: {1:7.2f} 
         Total Shipping is:           {2:7.2f} 
         The Total price is:          {3:7.2f}""".format(totalUnits, bookDiscountAmount
                                                         shipping, result)

这使得所有的数字都很好地对齐并且格式相同(小数点后有两位数字,总精度为7)。

编辑:当然,正如其他人指出的,不要硬编码那里的59

相关问题 更多 >

    热门问题