第6章 字典
6.1 一个简单的字典
6.2 使用字典
6.2.1 访问字典中的值
6.2.2 添加键—值对
6.2.3 先创建一个空字典
6.2.4 修改字典中的值
6.2.5 删除键—值对
6.2.6 由类似对象组成的字典
alien_0 = {
'color': 'green',
'points': 5
}
print(alien_0['color'])
print(alien_0['points'])
#添加键值
alien_0['x_position'] = 0
alien_0['y_position'] = 25
#创建空字典
alien_1 = {}
alien_1['color'] = 'green'
alien_1['points'] = 5
#修改键值
aline_0['color'] = 'yellow'
#删除
del aline_0['points']
#多行显示
print("aaaa " +
aline_0['color'].title() +
".")
6.3 遍历字典
6.3.1 遍历所有的键—值对
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for k, v in user_0.items():
print("\nKey: " + k)
print("Value: " + v)
#注意,即便遍历字典时,键—值对的返回顺序也与存储顺序不同。
6.3.2 遍历字典中的所有键
#for name in favorite_languages.keys():
#或者省略keys()也一样
#for name in favorite_languages
6.3.3 按顺序遍历字典中的所有键
#for name in sorted(favorite_languages.keys()):
6.3.4 遍历字典中的所有值
#for language in favorite_languages.values():
6.4 嵌套
6.4.1 字典列表
#创建字典加入列表
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15} 16
aliens = [alien_0, alien_1, alien_2]
# 创建一个用于存储外星人的空列表
aliens = []
# 创建30个绿色的外星人
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
# 显示前五个外星人
for alien in aliens[:5]:
print(alien)
print("...")
# 显示创建了多少个外星人
print("Total number of aliens: " + str(len(aliens)))
6.4.2 在字典中存储列表
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
print("\n" + name.title() + "'s favorite languages are:")
for language in languages:
print("\t" + language.title())
print("jen's favortate")
for name in favorite_languages['jen']:
print("\t" + name)
6.4.3 在字典中存储字典
users = {
'aeinstein': {
'first': 'albert',
'last' : 'einsterin',
'location' : 'princeton',
},
'mcurie' : {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
print("\nUsername:" + username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
print("\tFull name: " + full_name.title())
print("\tLocation:" + location.title())
第7章 用户输入和while循环
7.1 函数input()的工作原理
7.1.1 编写清晰的程序
7.1.2 使用int()来获取数值输入 输入的按做string 处理,需要转化 int(number)
7.1.3 求模运算符 %
7.1.4 在Python 2.7中获取输入 如果使用的是Python 2.7,请使用 raw_input() 而不是 input() 来获取输入。
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
7.2 while循环简介
7.2.1 使用while循环
7.2.2 让用户选择何时退出
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
message = input(prompt)
if message != 'quit':
print(message)
7.2.3 使用标志
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
7.2.4 使用break退出循环
if city == 'quit':
break
7.2.5 在循环中使用continue
7.2.6 避免无限循环
7.3 使用while循环来处理列表和字典
7.3.1 在列表之间移动元素
7.3.2 删除包含特定值的所有列表元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
#pets.pop()
print(pets)
7.3.3 使用用户输入来填充字典
responses = {}
polling_avtive = True
while polling_avtive:
name = input("\nWhat's your name?")
response = input("Which moutain would you like to climb?")
responses[name] = response
repeat = input("Would you like to continue? yes or no\n")
if repeat == 'no':
polling_avtive = False
print("\n ---- Polling Results ----")
for name, response in responses.items():
print(name.title() + "would you like to climb" + response + ".")
第8章 函数
8.1 定义函数
8.1.1 向函数传递信息
8.1.2 实参和形参
8.2 传递实参
8.2.1 位置实参
8.2.2 关键字实参
8.2.3 默认值
8.2.4 等效的函数调用
8.2.5 避免实参错误
def describe_pet(pet_name, animal_type='dog'):
"""显示宠物信息"""
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet("Cat", "Miao")
describe_pet(pet_name = 'harry', animal_type = 'hamster')
describe_pet(animal_type = 'hamster', pet_name = 'harry')
describe_pet('willie') #默认参数值
describe_pet(pet_name = 'willie')
8.3 返回值
8.3.1 返回简单值
8.3.2 让实参变成可选的
8.3.3 返回字典
8.3.4 结合使用函数和while循环
8.4 传递列表
8.4.1 在函数中修改列表
8.4.2 禁止函数修改列表
def print_models(unprinted_designs, completed_models):
"""
模拟打印每个设计, 打印完成,将其移动你刚到列表completed_models
"""
while unprinted_designs:
current_design = unprinted_designs.pop()
print("Printing model: " + current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
"""显示打印好的所有模型"""
print("\nThe following models have been printed.:")
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['iphone case','robot pendant','dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
#切片创建列表副本, 不修改列表
print_models(unprinted_designs[:], completed_models)
8.5 传递任意数量的实参
8.5.1 结合使用位置实参和任意数量实参
def make_pizza(size, *toppings):
"""概述要制作的比萨"""
print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
8.5.2 使用任意数量的关键字实参
def build_profile(first, last, **user_info):
"""创建字典"""
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key,value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert','einstein',
location = 'princetion',
field = 'physics')
print(user_profile)
8.6 将函数存储在模块中
8.6.1 导入整个模块
定义pissza的 函数, 8.5.1 范例,文件名pizza.py, 调用在另外的文件里
#文件名making_pizza.py
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
8.6.2 导入特定的函数
from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
8.6.3 使用as给函数指定别名
from pizza import make_pizza as mp 1
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
8.6.4 使用as给模块指定别名
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
8.6.5 导入模块中的所有
from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
8.7 函数编写指南
- 给形参指定默认值时,等号两边不要有空格:
- def function_name ( parameter_0 , parameter_1 =' default value ')
- 对于函数调用中的关键字实参,也应遵循这种约定:
- function_name ( value_0 , parameter_1 =' value ')
- 如果程序或模块包含多个函数,可使用两个空行将相邻的函数分开,这样将更容易知道前一个函数在什么地方结束,下一个函数从什么地方开始。
- 所有的 import 语句都应放在文件开头,唯一例外的情形是,在文件开头使用了注释来描述整个程序。