Unsatisfactory output


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

https://www.codecademy.com/courses/learn-python/lessons/a-day-at-the-supermarket/exercises/something-of-value-?action=lesson_resume

The code works fine, and codecademy asks me to proceed to the next lesson. But the results are whack. Anyone know why this happens? I can’t seem to figure out.



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

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

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


The results I get are as follows:

orange
price: 1.5
stock: 32

pear
price: 3
stock: 15

banana
price: 4
stock: 6

apple
price: 2
stock: 0
total: 48.0
total: 93.0
total: 117.0
total: 117.0


#2

This variable is declared in a different scope, perhaps?


#3

I still don’t quite get it.


#4

This only needs to print at the completion of the loop.


#5

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

for key in prices:
print
print key
print “price: %s” % prices[key]
print “stock: %s” % stock[key]
print

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

Ok so this gave the correct output, although I personally think that the code below gives a prettier output.

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

for key in prices:
print
print key
print “price: %s” % prices[key]
print “stock: %s” % stock[key]

total = 0
total += prices[key] * stock[key]
print 'total: ', total

Thank you heaps for the help. =)


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.