Scope newbie problem for loop in python


#1



I'm having a problem with 9.something of Value > "A day at the Supermarket" task in free Python beginner course, here is a link:
Python beginner tutorial , "A Day at Supermarket"


I have this strange error message:

Oops, try again. It looks like your code did not print the correct total.

I really don't understand what is wrong with my code, I tried to add "global" keyword, because this is a scope problem (?), but the editor throws then "syntax error". I did some research on google but this must be very newbie question because i didn't find any solutions.

prices = {
    "banana" : 4,
    "apple"  : 2,
    "orange" : 1.5,
    "pear"   : 3
}
stock = {
    "banana" : 6,
    "apple"  : 0,
    "orange" : 32,
    "pear"   : 15
}

for key in prices:
    print key
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]
    
total = 0

for key in prices:
    prices[key] = prices[key] * stock[key]
    print prices[key]
    total = total + prices[key]
print total

Here is my console output:
> orange
> price: 1.5
> stock: 32
> pear
> price: 3
> stock: 15
> banana
> price: 4
> stock: 6
> apple
> price: 2
> stock: 0
> 48.0
> 45
> 24
> 0
> 117.0
> None


#2

Hi @koloboss12 ,

What is the purpose of this statement, and does it accomplish that purpose without degrading the validity of the data? ...

prices[key] = prices[key] * stock[key]

#3

Thanks @appylpye
I thought that dictionary must be updated. So this was more english than python problem ;p
After changing this line into line with new local var it worked.
But i still don't understand why the scope error occurs? I tried to print total and it was printed (console output proves that).


#4

You do not need to use the global keyword here, since all your names are declared outside any function, and are therefore already global.

The dictionaries should not be updated in this exercise. Instead, revise the inside of the loop that begins with the header ...

for key in prices:

The only task that the inside of the loop should perform is to increment the value of total by prices[key] * stock[key] during each iteration.

It later exercises, but not here, you will need to update the stock dictionary. The prices dictionary will be left as is.


#5

Your total of 117.0 was actually correct, but your having altered the prices dictionary messed up the performance of Codecademy's submission correctness test (SCT).


#6

Ok now it's clear, thanks!


#7