The program I am trying to write is as follows

- asks the user how many books they bought

- asks the user the cost of each book

- if they buy 4 or more books, they receive a 40% discount on their purchase

-if they buy 3 books, they receive a 30% discount on their purchase

-if they buy 2 books, they receive a 20% discount on their purchase

-if they buy 1 book, they receive a 10% discount on their purchase

- must write the code using functions

-must call the function in from another module (using ECLIPSE IDE with pythonviewer)

My approach was to first find the total of the books using a for loop and then using if statements, i would apply the proper discount to the total to get the grand total. I have been able to run this code, but I cannot get the right answer if 4 books are purchased (discount doesnt apply properly) OR only one book is purchased (get error: local variable 'grand_total' referenced before assignment)

Here is my code:

- Code: Select all
`def total_cost (numbooks):`

total = 0

for numbooks in range(numbooks):

price_each_book = int(input("price of the book?"))

total = total + price_each_book

if numbooks >= 5:

grand_total = total - (total * 0.4)

elif numbooks == 4:

grand_total = total - (total * 0.4)

elif numbooks ==3:

grand_total = total - (total * 0.3)

elif numbooks ==2:

grand_total = total - (total * 0.2)

elif numbooks ==1:

grand_total = total - (total * 0.1)

return grand_total

and to call and run the function from another module:

- Code: Select all
`import maggiespizza`

numbooks = int(input("How many books are you buying?"))

s = maggiespizza.total_cost(numbooks)

print ("total: {0} " .format(s))

Any help would be appreciate, thanks for your time!