我正在阅读这本名为“用于软件设计的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)
这样,我得到以下结果:
总价为:945.45
我的问题是:
只需更改三件事:
1)您重复了书籍的数量:60和59都出现在代码中。你不应该在那里有59。
2)打印结果如下: print 'The total price is: %.2f' % result
3)通常的Python约定是将变量命名为variables_like_this,而不是LikeThis。
所以一个好方法是执行以下操作?
shipping = shippingPriceRest * totalUnits - 1 + shippingPriceFirst
如果尝试这样做,您将看到需要包含一些括号以使其评估您的意思。