Making a purchase


#1

def compute_bill(food):
    for item in food:
        total = 0
        total = total+prices[item]
        return total

what is wrong with that code


#2

in each run of your loop, total is resetted to zero, place this before the loop

your loop only runs once, since in the first run a return keyword is reached. (function ends the moment a return keyword is reached). Change the indention so the whole loop can run


#3

dont understand plz explain with code


#4

in each run of your loop:

for item in food:
        total = 0

total is assigned a value of zero, so all the sums you do here:

total = total+prices[item]

is reset each time, place the declaration of total outside the for loop.

The function ends the moment a return keyword is reached:

return total

which in your case happens in the first run of the loop. Change the indention of the return so the whole loop can run


#5

def compute_bill(food):
for item in food:
total = 0
total = total+prices[item]
return total
still there is error


#6

Oops, try again. compute_bill(['apple']) resulted in an UnboundLocalError: local variable 'total' referenced before assignment this the error


#7

can i see your full code? please use markup:


#8

shopping_list = ["banana", "orange", "apple"]

stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}

prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}

Write your code below!

def compute_bill(food):
for item in food:
total =0
total = total + prices[item]
return total


#9

In spite of all the help you have been given you still have not corrected any errors. total needs to be initialized before the loop, and the return statement should not be inside the loop.

def compute_bill(food):
    total = 0
    for item in food:
        total += prices[item]
    return total

#10

so i know what is wrong now thanks body it was the return
the return has to be under for like that
for item in food:
total += prices[item]
return total
but total isnt under for


#11

Dude ! I can't believe it ! I just changed the indentation (took 1 tab off) and it worked !

It really is indent-sensitive. You won't get away with anything here .....


#12

it is python, python uses indent rather then curly brackets (like javascript)


#13

Thank you I really appreciate everything that comes out of you mate ......


#14

Yeah JS really kicks my butt ..... heh ....


#15

could you please tell us why return should not be inside the loop ?


#16

Because we need to permit the iteration to complete so the total is correct.