I just started learning Python and i find it really easy to use although it gets me a bit confused when i have to use the %s/d/f in exercises.
prices = {
“banana” : 4,
“apple” : 2,
“orange” : 1.5,
“pear” : 3
}
stock = {
“banana” : 6,
“apple” : 0,
“orange” : 32,
“pear” : 15
}
for item in prices:
print item
print “price: %s” % prices[item]
print “stock: %s” % stock[item]
As in this code sequence for example I don’t really understand why i should use %s when the value corresponding to the key is an integer. ( the last two rows)
I guess you could use %d for integers and %f for floats.
%s is for strings,
but I guess Python can convert it if its not a string in this case.
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15
}
for item in prices:
print( item )
print( " price: %.2f" % prices[item] )
print( " stock: %d" % stock[item] )
[/quote]
1 Like
I see. I will try to use it in more situations like you did so that i can learn better. Thanks!
system
Closed
November 4, 2022, 2:50am
#4
This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.