Something of value confusion


#1



https://www.codecademy.com/courses/python-beginner-en-IZ9Ra/1/4?curriculum_id=4f89dab3d788890003000096#

I got the exercise right with help but confused by the use of this code:print "price: %s" % prices[key]
print "stock: %s" % stock[key]
memory's a bit rough of the previous exercises so an explanation would help.

Thanks in advance.


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


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


#2

I believe this is called modulo formatting.

"string with %args" % kwargs

Inside the string, the modulo arguments are,

%s  => string object expected in keyword arguments

%i  => integer object expected in kwargs

%d  => double precision integer expected in kwargs

%f  => float object expected in kwargs

%r  => representation object (list, dictionary) expected in kwargs

This is not an exhaustive list but the most common types expressed.


#3

Sorry to say but I'm still not getting it :confused:
Because as the instruction says: Loop through the prices dictionaries.
For each key in prices, multiply the number in prices by the number in stock. Print that value into the console and then add it to total.
Doesn't make sense with the code for me.


#4

I'm not sure where the confusion is. Your code is correct so you must have some idea, unless the code is copied and you are just trying to understand it.


#5

the instruction gave a similar code so I just replaced some words and it worked so I kind of also need to understand it if you are willing to explain.


#6

Let's start with the above line. Do you understand what this line is doing?


#7

Yes.........I.....do
dots for the sake of 20 characters :£


#8

So we are iterating over a dictionary which has keys in common with another dictionary.

total = 0
for key in prices and stock:   # legitimate way to show both dictionaries
    print key                  # prints one of, banana, pear, apple, or orange
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]
    total += prices[key] * stock[key]
print total

Given key is banana, the output will be,

banana
price: 4
stock: 6

total will now read 24 when we add 4 * 6.

"string content %s" % variable
                 ^        ^
                 |        |
         placeholder for  |
                        this guy

#9

Really helpful, thanks.


#10

so in conclusion basically %s' job is to be a placeholder ?


#11

That is correct. See the earlier post for the various descriptors denoting expected data type.