<a href="http://www.jianshu.com/p/54870e9541fc">总目录</a>
课程页面:https://www.codecademy.com/
内容包含课程笔记和自己的扩展折腾
价目表,库存,打印每样物品价格库存
prices = {
"avocado": 2,
"banana": 1,
"apple": 1,
"date": 5
}
stock = {
"avocado": 50,
"banana": 100,
"apple": 80,
"date": 25
}
for x in prices:
print x
print "prices: %s" % prices[x]
print "stock: %s" % stock[x]
Output:
date
prices: 5
stock: 25
avocado
prices: 2
stock: 50
banana
prices: 1
stock: 100
apple
prices: 1
stock: 80
Process finished with exit code 0
- 换种方法折腾一下:
prices_stock = {
"avocado": [2, 50],
"banana": [1, 100],
"apple": [1, 80],
"date": [5, 25],
}
for x in prices_stock:
print "%s \n prices: %s \n stock: %s \n ===" % \
(x, prices_stock[x][0], prices_stock[x][1])
Output:
date
prices: 5
stock: 25
===
avocado
prices: 2
stock: 50
===
banana
prices: 1
stock: 100
===
apple
prices: 1
stock: 80
===
Process finished with exit code 0
评价:这方法不好。虽然代码少,但是如果list内容之后增多,写程序容易出错,不方便记忆。
打印库存总市值
total_value = 0
for x in prices:
print x + ":"
print prices[x] * stock[x]
total_value += prices[x] * stock[x]
print
print "total value: %s" % total_value
Output:
date:
125
avocado:
100
banana:
100
apple:
80
total value: 405
Process finished with exit code 0
打印购物车账单
给定一个shopping list,然后反馈价格
prices = {
"avocado": 2,
"banana": 1,
"apple": 1,
"date": 5
}
stock = {
"avocado": 50,
"banana": 100,
"apple": 80,
"date": 2
}
shopping_list = ["avocado", "avocado", "date", "date", "date", \
"date", "banana", "banana", "banana"]
def complete_bill(food):
total = 0
out_of_stock_num = 0
for x in food:
if stock[x] > 0:
total += prices[x]
stock[x] -= 1
else:
print "One " + x + " is out of stock."
out_of_stock_num += 1
return (total, out_of_stock_num)
total, out_of_stock_num = complete_bill(shopping_list)
if out_of_stock_num == 0:
print "You should pay £%s." % (total)
elif out_of_stock_num == 1:
print "There is one item out of stock. You should pay £%s." \
% (total)
else:
print "There are %s items out of stock. You should pay £%s." \
% (out_of_stock_num, total)
Output:
One date is out of stock.
One date is out of stock.
There are 2 items out of stock. You should pay £17.