温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Help with a python code
python

其他 - 帮助使用python代码

发布于 2020-03-29 12:54:40

我正在阅读这本名为“用于软件设计的Python”的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

  • 我的问题是:

    • 它是否正确?
    • 我怎样才能使这段代码更好?

查看更多

查看更多

提问者
philberndt
被浏览
12
Ned Batchelder 2011-06-27 22:14

只需更改三件事:

1)您重复了书籍的数量:60和59都出现在代码中。你不应该在那里有59。

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

3)通常的Python约定是将变量命名为variables_like_this,而不是LikeThis。