[第三周]第六章课后练习

6-2 喜欢的数字 :使用一个字典来存储一些人喜欢的数字。请想出5个人的名字,并将这些名字用作字典中的键;想出每个人喜欢的一个数字,并将这些数字作为值存储在字典中。打印每个人的名字和喜欢的数字。为让这个程序更有趣,通过询问朋友确保数据是真实的。

favorite_numbers={'Sister':8,'Shijia':7,'Peiwei':3,'Shulin':9,'Yuchen':1}
for name,number in favorite_numbers.items():
    print(name + "'s favorite number is " + str(number) )

输出:

Sister's favorite number is 8
Shijia's favorite number is 7
Peiwei's favorite number is 3
Shulin's favorite number is 9
Yuchen's favorite number is 1

6-5 河流 :创建一个字典,在其中存储三条大河流及其流经的国家。其中一个键—值对可能是’nile’: ‘egypt’ 。
·使用循环为每条河流打印一条消息,如“The Nileruns throughEgypt.”。
·使用循环将该字典中每条河流的名字都打印出来。
·使用循环将该字典包含的每个国家的名字都打印出来

river_countries={'nile':'egypt','amazon river':'brazil','yangtze river':'china'}
for river,country in river_countries.items():
    print("The " + river.title() + " runs through " + country.title()+".")
print("\n")

for river in river_countries.keys():
    print(river.title())
print("\n")

for country in river_countries.values():
    print(country.title())

输出:

The Nile runs through Egypt.
The Amazon River runs through Brazil.
The Yangtze River runs through China.


Nile
Amazon River
Yangtze River


Egypt
Brazil
China

6-8 宠物 :创建多个字典,对于每个字典,都使用一个宠物的名称来给它命名;在每个字典中,包含宠物的类型及其主人的名字。将这些字典存储在一个名为pets 的列表中,再遍历该列表,并将宠物的所有信息都打印出

cat={'type':'cat','host_name':'Alice'}
dog={'type':'dog','host_name':'Bob'}
rabbit={'type':'rabbit','host_name':'Celina'}
pig={'type':'pig','host_name':'Zpeiwei'}
pets=[cat,dog,rabbit,pig]
for pet in pets:
    print(pet)

输出:

{'type': 'cat', 'host_name': 'Alice'}
{'type': 'dog', 'host_name': 'Bob'}
{'type': 'rabbit', 'host_name': 'Celina'}
{'type': 'pig', 'host_name': 'Zpeiwei'}

6-10 喜欢的数字 :修改为完成练习6-2而编写的程序,让每个人都可以有多个喜欢的数字,然后将每个人的名字及其喜欢的数字打印

favorite_numbers={'Sister':[1,3,5],'Zpeiwei':[3,4,7],'Shulin':[9,1]}
for name,numbers in favorite_numbers.items():
    print(name + "'s favorite numbers are ")
    for number in numbers:
        print(number)

输出:

Sister's favorite numbers are
1
3
5
Zpeiwei's favorite numbers are
3
4
7
Shulin's favorite numbers are
9
1

6-11 城市 :创建一个名为cities 的字典,其中将三个城市名用作键;对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。在表示每座城市的字典中,应包含country 、population 和fact 等键。将每座城市的名字以及有关它们的信息都打印出

wuhan={'country':'China','population':1000000,'fact':"It's really hot!"}
new_york={'country':'US','population':100000,'fact':"Beautiful!"}
guangzhou={'country':'China','population':1000000,'fact':"Food here is delicious!"}
cities={'wuhan':wuhan,'new york':new_york,'guangzhou':guangzhou}
for city,information in cities.items():
    print(city.title()+":")
    print(information)

输出:

Wuhan:
{'country': 'China', 'population': 1000000, 'fact': "It's really hot!"}
New York:
{'country': 'US', 'population': 100000, 'fact': 'Beautiful!'}
Guangzhou:
{'country': 'China', 'population': 1000000, 'fact': 'Food here is delicious!'}

猜你喜欢

转载自blog.csdn.net/shu_xi/article/details/79644875