How to Return a Shopping Cart Total

Question:

I’ve been at this for hours and I just can’t seem to figure out how to return a total. All I know is that I need to start with total = 0. I have tried ‘for i in x’ loops and I wish I had them to post here but I’ve been doing trial and error for so long that I can’t exactly recall what I’ve done. I’m using Python 2.7.10 and I’m a complete beginner. Please help? Even if just a hint?

f_list = []
print 'Enter a fruit name (or done):',
f = raw_input()
while f != 'done':
    print 'Enter a fruit name (or done):',
    f_list.append(f)
    f = raw_input()
print ""
p_list = []
for i in f_list:
    print 'Enter the price for ' + i + ':',
    p = float(raw_input())
    p_list.append(p)
print ""
print 'Your fruit list is: ' + str(f_list)
print 'Your price list is: ' + str(p_list)
print ""
n = len(f_list)
r = range(0,n)
q_list = []
for i in r:
    print str(f_list[i]) + '(' + '$' + str(p_list[i]) + ')',
    print 'Quantity:',
    q = raw_input()
total = 0
Asked By: Gkew

||

Answers:

There are definitely other answers on this site that should help you, but you want to convert your q to a float and append q to q_list just like for p. To get your grand total all you need to do is total = sum(q_list) and display your answer.

Answered By: Michael Russo

You have forgotten to create the list of quantities, which isn’t going to help.
Then just iterate over your f_list and add them up.

f_list = []
print 'Enter a fruit name (or done):',
f = raw_input()
while f != 'done':
    print 'Enter a fruit name (or done):',
    f_list.append(f)
    f = raw_input()
print ""
p_list = []
for i in f_list:
    print 'Enter the price for ' + i + ':',
    p = float(raw_input())
    p_list.append(p)
print ""
print 'Your fruit list is: ' + str(f_list)
print 'Your price list is: ' + str(p_list)
print ""
q_list = []
for i in range(len(f_list)):
    print str(f_list[i]) + '(' + '$' + str(p_list[i]) + ')',
    print 'Quantity:',
    q = raw_input()
    q_list.append(q)
total = 0
for i in range(len(f_list)):
    total += float(p_list[i]) * int(q_list[i])
print "Basket value : ${:.2f}".format(total) 
Answered By: Rolf of Saxony
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.