Python 你能解释一下吗,我的一节课

Python 你能解释一下吗,我的一节课,python,Python,我在codecademy上学习代码。当我在其中编码时,我没有得到练习的解决方案,我单击了给我解决方案选项 我得到了解决方案,因为我不理解程序。程序是这样的 prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3} stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15} for food in prices: print food print "price: %s"

我在codecademy上学习代码。当我在其中编码时,我没有得到练习的解决方案,我单击了给我解决方案选项 我得到了解决方案,因为我不理解程序。程序是这样的

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

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

for food in prices:
  print food
  print "price: %s" % prices[food]
  print "stock: %s" % stock[food]
然后打印出来

orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
banana
price: 4
stock: 6
apple
price: 2
stock: 0
你能解释一下这个过程吗。
它如何打印上面给出的输出

了解这个问题会很有帮助。但我可以尝试在不知道问题的情况下,从高层次上解释这个项目

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

stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}
这是两本词典的定义,第一本词典只存储每个水果的价格,第二本词典存储仓库(库存)中有多少水果


顺便说一下,这看起来像Python2语法,因为
print
语句中没有括号。我强烈建议您学习Python 3

您有两本词典,分别名为
价格
股票

prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}
stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}
您正在迭代
价格
dict by
获取食品价格:
此行

阅读此代码的注释:

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

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

for food in prices: #iterate over the keys of prices dict
  print food #print the key
  print "price: %s" % prices[food] #print the value of prices dict at food key
  print "stock: %s" % stock[food] #print the value of stock dict at food key

但在这个项目中,你到底不清楚什么?
prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3} #prices dict

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

for food in prices: #iterate over the keys of prices dict
  print food #print the key
  print "price: %s" % prices[food] #print the value of prices dict at food key
  print "stock: %s" % stock[food] #print the value of stock dict at food key