Python编程-从入门到实践(第2版)第六章练习代码

练习6-1:人

使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居住的城市。该字典应包含键 first_name、 last_name、 age 和 city。将存储在该字典中的每项信息都打印出来
# 创建字典
friend = {
    'first_name' : 'lesion',
    'last_name' : 'chen',
    'age' : 18,
    'city' : 'beijing',
}

# 打印字典中的信息
print(friend['first_name'].title() + ' ' + friend['last_name'].title()
     + ' ' + str(friend['age']) + ' ' + friend['city'].title())

练习6-2:喜欢的数字

使用一个字典来存储一些人喜欢的数字。请想出 5 个人的名字,并将这些名字用作字典中的键;想出每个人喜欢的一个数字,并将这些数字作为值存储在字典中。打印每个人的名字和喜欢的数字。为让这个程序更有趣,通过询问朋友确保数据是真实的
# 创建字典
favorite_num = {
    'A' : 1,
    'B' : 2,
    'C' : 3,
    'D' : 4,
    'E' : 5
}

# 输出最喜欢的数字
print("What is your favorite number?")
print(f"A's favorite number is {favorite_num['A']}")
print(f"B's favorite number is {favorite_num['B']}")
print(f"C's favorite number is {favorite_num['C']}")
print(f"D's favorite number is {favorite_num['D']}")
print(f"E's favorite number is {favorite_num['E']}")

练习6-3:词汇表

Python 字典可用于模拟现实生活中的字典,但为避免混淆,我们将后者称为词汇表
  • 想出你在前面学过的 5 个编程词汇,将它们用作词汇表中的键,并将它们的含义作为值存储在词汇表中
  • 以整洁的方式打印每个词汇及其含义。为此,你可以先打印词汇,在它后面加上一个冒号,再打印词汇的含义;也可在一行打印词汇,再使用换行符( \n)插入一个空行,然后在下一行以缩进的方式打印词汇的含义
# 创建字典
code_lang = {
    'if' : '条件检验',
    '=' : '赋值',
    '==' : '验证是否相等',
    'False' : 'bool值, 假',
    'True' : 'bool值, 真'
}

# 输出术语含义
print(f"'if' means {code_lang['if']}.\n")
print(f"'=' means {code_lang['=']}.\n")
print(f"'==' means {code_lang['==']}.\n")
print(f"'False' means {code_lang['False']}.\n")
print(f"'True' means {code_lang['True']}.\n")

练习6-4:词汇表2

既然你知道了如何遍历字典,现在请整理你为完成练习 6-3 而编写的代码,将其中的一系列 print 语句替换为一个遍历字典中的键和值的循环。确定该循环正确无误后,再在词汇表中添加 5 个 Python 术语。当你再次运行这个程序时,这些新术语及其含义将自动包含在输出中
# 创建字典
code_lang = {
    'if' : '条件检验',
    '=' : '赋值',
    '==' : '验证是否相等',
    'False' : 'bool值, 假',
    'True' : 'bool值, 真',
    '!=' : '不等于',
    'elif' : '验证另一种情况',
    'else' : '条件验证不通过时执行的代码',
    '>=' : '大于等于',
    '<=' : '小于等于',
}

# 输出术语
for key, value in code_lang.items():
    print(f"{key} means {value}.")

练习6-5:河流

创建一个字典,在其中存储三条大河流及其流经的国家。其中一个键—值对可能是'nile': 'egypt'
  • 使用循环为每条河流打印一条消息,如“The Nile runs through Egypt.”
  • 使用循环将该字典中每条河流的名字都打印出来
  • 使用循环将该字典包含的每个国家的名字都打印出来
# 创建河流键值对
river_country = {
    'nile river' : 'egypt',
    'yellow river' : 'china',
    'yangtse river' : 'china',
    'amazon river' : 'south america',
    'mississippi River' : 'america',
}

# 循环字典输出河流和国家
for river, country in river_country.items():
    print(f"The {river.title()} runs through {country.title()}.")

# 循环字典中的河流
for river in river_country.keys():
    print(river.title())

# 循环字典中的国家
for country in river_country.values():
    print(country.title())

练习6-6:调查

在 6.3.1 节编写的程序 favorite_languages.py 中执行以下操作
  • 创建一个应该会接受调查的人员名单,其中有些人已包含在字典中,而其他人未包含在字典中
  • 遍历这个人员名单,对于已参与调查的人,打印一条消息表示感谢。对于还未参与调查的人,打印一条消息邀请他参与调查
# 创建字典
favorite_languages = {
        'jen':'python',
        'sarsh':'c',
        'edward':'ruby',
        'phil':'python',
        }

# 创建列表,其中有部分人在字典中,有部分人不在字典中
candidates = ['jen', 'tom', 'lesion', 'edward', 'sarsh', 'john', 'lucy']

# 循环candidates
for candidate in candidates:
    # 检验是否在字典中
    if candidate in favorite_languages.keys():
        print(f"Thank you, {candidate.title()}! ")
    else:
        print(f"Hey {candidate.title()}! What's your favorite language?")

练习6-7:

在为完成练习 6-1 而编写的程序中,再创建两个表示人的字典,然后将这三个字典都存储在一个名为 people 的列表中。遍历这个列表,将其中每个人的所有信息都打印出来
# 创建字典
friend_1 = {
    'first_name' : 'lesion',
    'last_name' : 'chen',
    'age' : 18,
    'city' : 'beijing',
}

friend_2 = {
    'first_name' : 'master',
    'last_name' : 'zhang',
    'age' : 99,
    'city' : 'nanjing',
    }

friend_3 = {
    'first_name' : 'big dick',
    'last_name' : 'hsue',
    'age' : 99999,
    'city' : 'boston',
}

# 创建列表,并将字典放入列表中
friends = [friend_1, friend_2, friend_3]

# 遍历列表
for friend in friends:
    # 输出字典中的元素
    print(f"My name is {friend['first_name'].title()} {friend['last_name'].title()}, I'm {friend['age']} years old and living in {friend['city'].title()}!")
    print("That's thank you!")

练习6-8:宠物

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

snooby = {
    'type' : 'dog',
    'master' : 'disney',
}

tom = {
    'type' : 'cat',
    'master' : 'landlady',
}

jerry = {
    'type' : 'mouse',
    'master' : 'no one',
}

# 创建列表
pets = [bibi, snooby, tom, jerry]

# 循环列表,输出宠物信息
for pet in pets:
    print(f"{pet['master'].title()} has a {pet['type'].title()}.")

练习6-9:喜欢的地方

创建一个名为 favorite_places 的字典。在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的 1~3 个地方。为让这个练习更有趣些,可让一些朋友指出他们喜欢的几个地方。遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。
# 创建一个字典
favorite_places = {
    'master zhang' : ['tokyo', 'shanghai', 'changzhou'],
    'dick hsue' : ['boston', 'hefei', 'xiamen'],
    'teacher wang' : ['tianjing', 'beijing', 'chengde'],
}

# 遍历字典
for name, places in favorite_places.items():
    for place in places:
        print(f"{name.title()} wanna go to {place.title()}!")
    print(f"That's what {name.title()} likes.")

练习6-10:喜欢的数2

修改为完成练习6-2而编写的程序,让每个人都可以有多个喜欢的数字,然后将每个人的名字以及喜欢的数字打印出来。
# 创建字典
favorite_num = {
    'a' : [1, 2, 3, 4, 5],
    'b' : [6, 7, 8, 9, 10],
    'c' : [11, 12, 13, 14, 15],
    'd' : [16, 17, 18, 19, 20],
    'e' : [21, 22, 23, 24 ,25],
}

# 遍历字典
for name, numbers in favorite_num.items():
    print(f"What is {name.title()} favorite number?")
    for number in numbers:
        print(f"His favorite number is {number}.")

练习6-11:城市

创建一个名为 cities 的字典,其中将三个城市名用作键;对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。在表示每座城市的字典中,应包含 country、 population 和 fact 等键。将每座城市的名字以及有关它们的信息都打印出来。
# 创建字典
cities = {
    # 字典中嵌套字典
    'fuzhou' : {
        'country' : 'china',
        'population' : 2000000,
        'fact' : 'There is lots of trees.',
    },

    'boston' : {
        'country' : 'america',
        'population' : 500000,
        'fact' : 'There is lots of famous universities.',
    },

    'london' : {
        'country' : 'england',
        'population' : 450000,
        'fact' : 'it is a garbage city.'
    },
}

# 遍历字典
for city, city_info in cities.items():
    print(f"{city.title()} is in {city_info['country'].title()} and its population is {str(city_info['population'])}, we all know that {city_info['fact']}.")
#Python##自学#
全部评论

相关推荐

3 1 评论
分享
牛客网
牛客企业服务