帮助解决Python代码问题

1 投票
11 回答
24229 浏览
提问于 2025-04-16 20:22

我正在读一本叫《软件设计中的Python》的书,里面有这样一个练习:

假设一本书的定价是24.95美元,但书店可以享受40%的折扣。运费是第一本书3美元,之后每本书运费是75美分。那么,60本书的总批发成本是多少呢?

好的,我写了以下代码:

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

  • 我有几个问题:

    • 这样计算正确吗?
    • 我该如何改进这段代码?

11 个回答

1

我建议的唯一改进是使用 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)

这样可以让所有的数字对齐得很好,并且格式一致(小数点后有两位数字,总共精确到七位)。

补充:当然,正如其他人提到的,不要把 59 这个数字写死在代码里。

1

我觉得这样写没问题。不过我建议不要直接写59这个数字。可以先检查一下总数是否大于1,然后再根据情况进行划分。

另外,这个是小问题,但bookDiscountAmount应该改成bookDiscountedAmount(折扣是他们省下来的金额,而不是他们实际支付的金额)。还有其他人也提到过如何改进字符串的输出。

6

需要改动的地方只有三个:

1) 你重复了书籍的数量:代码中同时出现了60和59。其实不应该有59这个数字。

2) 输出结果的格式应该是这样的:print '总价格是: %.2f' % result

3) 在Python中,通常的命名规则是用下划线分隔单词,比如变量名应该写成这样:variables_like_this,而不是像这样:notLikeThis。

撰写回答