我正在阅读这本名为“软件设计的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)
我得到了以下结果:
总价为:945.45
我的问题是:
在我看来是对的。我会避免硬编码59。取而代之的是,检查总数是否超过一个,并根据需要进行划分。
而且,这是次要的,但是
bookDiscountAmount
应该是bookDiscountedAmount
(折扣是他们节省的金额,而不是他们支付的金额)。其他人已经指出如何改进字符串打印。只有三件事需要改变:
1)您复制了图书数量:60本和59本都出现在代码中。你不应该有59个在里面。
2)按如下方式打印结果:
print 'The total price is: %.2f' % result
3)通常的Python约定是像这样命名变量,而不是像这样命名。
我建议的唯一改进是使用
format
-函数而不是字符串连接:这使得所有的数字都很好地对齐并且格式相同(小数点后有两位数字,总精度为7)。
编辑:当然,正如其他人指出的,不要硬编码那里的
59
。相关问题 更多 >
编程相关推荐