前言
A Day at the Supermarket该项目用来回顾/强化之前学习Python的知识点。
1、Before We Begin
names = ["Adam","Alex","Mariah","Martine","Columbus"]
for elements in names:
print elements
上述代码,使用for循环,将names这个list中的items逐个输出/打印出来——遍历。
2、This is Key!
对dictionary使用for循环,输出是无序的,即每次输出,“key/value对”的顺序是无序的。
webster = {
"Aardvark" : "A star of a popular children's cartoon show.",
"Baa" : "The sound a goat makes.",
"Carpet": "Goes on the floor.",
"Dab": "A small amount."
}
# Add your code below!
for key in webster:
print webster[key]
3、Control Flow and Looping
在循环中,有选择性地输出数据
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
for item in a:
if item % 2 == 0:
print item
4、Lists + Functions
函数可以将List作为其输入参数,进行下一步操作运算
任务:Write a function that counts how many times the string
"fizz"
appears in a list.
# Write your function below!
def fizz_count(x):
count = 0
for item in x:
if item == "fizz":
count += 1
return count
fizz_count(["fizz","cat","fizz"])
5、String Looping
字符串和list类似,其每个字符相当于元素,所以字符串也可以像list一样循环操作。
可参见下述代码:
for letter in "Codecademy":
print letter
# Empty lines to make the output pretty
print
print
word = "Programming is fun!"
for letter in word:
# Only print out the letter i
if letter == "i":
print letter
6、Your Own Store!
创建一个价格dictionary——prices
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
7、Investing in Stock
创建一个库存dictionary——stock
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
8、Keeping Track of the Produce
输出价格和库存信息
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
for key in prices:
print key
print "price: %s" % prices[key]
print "stock: %s" % stock[key]
9、Something of Value
将每种商品的总价格及所有商品的价格计算并打印出来total = 0
for key in prices:
print "prices: %s" % prices[key]*stock[key]
total += prices[key]*stock[key]
print total
10、Shopping at the Market
groceries = ["banana", "orange", "apple"]
11、Making a Purchase
计算自己选购商品的价格
def compute_bill(food):
total = 0
for item in food:
total += prices[item]
stock[item] -= 1
return total
12、Stocking Out
提示:If you're buying a banana, check if it's in stock (larger than zero). If it's in stock, add the cost of a banana to your bill. Finally, decrement the stock of bananas by one!
def compute_bill(food):
total = 0
for item in food:
if stock[item] > 0:
total += prices[item]
stock[item] -= 1
return total
上述已经完成list、dictionary的创建
- ——Using
for
loops with lists and dictionaries - ——Writing functions with loops, lists, and dictionaries
- ——Updating data in response to changes in the environment (for instance, decreasing the number of bananas in
stock
by 1 when you sell one). - 完整代码如下:
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
# Write your code below!
def compute_bill(food):
total = 0
for item in food:
if stock[item] > 0:
total += prices[item]
stock[item] -= 1
return total