Warm tip: This article is reproduced from stackoverflow.com, please click
python

Help with a python code

发布于 2020-03-29 12:46:27

I'm reading this python book called "Python for software design" and it has the following exercise:

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

ok, i have the following code:

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)

With that I get the following results:

  • The total price for 60 books including shipping and discount is:
  • Total price of the books is: 898.2
  • Total Shipping is: 47.25
  • The Total price is: 945.45

  • My questions are:

    • Is this correct?
    • How can i make this code better?
Questioner
philberndt
Viewed
29
Ned Batchelder 2011-06-27 22:14

There are only three things to change:

1) You duplicated the number of books: 60 and 59 both appear in the code. You shouldn't have 59 in there.

2) Print you results like this: print 'The total price is: %.2f' % result

3) Usual Python convention is to name variables_like_this, notLikeThis.