for key, value in user_0.items():print("Key: "+ key)print("Value: "+ value)
不关心字典键值对的顺序,只跟踪键值对的关联关系。
keys返回字典键列表,遍历字典所有键:
for name in favorite_languages.keys():print(name.title())//或
for name in favorite_languages:print(name.title())
sorted按顺序遍历字典中的所有键。
values返回字典值列表,遍历字典所有值:
for language in favorite_languages.values():print(language.title())
set对字典中的值去重。
第7章 用户输入和while循环
input提示用户输入,输入参数为提示信息,返回结果为用户输入值。
input将用户输入解读为字符串。
int将字符串转为数字。
python2中获取用户输入使用raw_input。
务必确保循环可以按预期结束。
for循环中不应修改列表,否则会导致难以跟踪其中的元素。
第8章 函数
关键字实参和实参顺序无关,但务必准确指定函数中定义的形参名:
defdescribe_pet(animal_type, pet_name):"""显示宠物的信息"""print("I have a "+ animal_type +".")print("My "+ animal_type +"'s name is "+ pet_name.title()+".")
describe_pet(animal_type='hamster', pet_name='harry')
使用参数默认值时,必须先列出没有默认值的形参,再列出有默认值的实参。
将列表传递给函数后,在函数中对列表做的修改都是永久性的。
如果需要禁止函数修改列表,可以向函数传递列表副本:
function_name(list_name[:])
任意数量实参,实参会封装到一个元组中:
defmake_pizza(*toppings):"""概述要制作的比萨,toppings是一个元组"""print("\nMaking a pizza with the following toppings:")for topping in toppings:print("- "+ topping)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
Making a pizza with the following toppings:- pepperoni
Making a pizza with the following toppings:- mushrooms
- green peppers
- extra cheese
结合位置实参和任意数量实参:
defmake_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')
Making a 16-inch pizza with the following toppings:- pepperoni
Making a 12-inch pizza with the following toppings:- mushrooms
- green peppers
- extra cheese
任意数量的关键字实参:
defbuild_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='princeton',
field='physics')print(user_profile)