Python编程:从入门到实践(第2版)第六章课后题

第六章

6.2

练习6-1:人  使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居 住的城市。该字典应包含键first_name 、last_name 、age 和city 。将 存储在该字典中的每项信息都打印出来。

person = {
    'first_name': 'John',
    'last_name': 'Doe',
    'age': 30,
    'city': 'New York'
}

print("First Name:", person['first_name'])
print("Last Name:", person['last_name'])
print("Age:", person['age'])
print("City:", person['city'])

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

favorite_numbers = {
    'Alice': 7,
    'Bob': 12,
    'Charlie': 42,
    'David': 3,
    'Eva': 9
}

for name, number in favorite_numbers.items():
    print(f"{name}'s favorite number is {number}.")

练习6-3:词汇表  Python字典可用于模拟现实生活中的字典。为避免混淆, 我们将后者称为词汇表。

  • 想出你在前面学过的5个编程术语,将其用作词汇表中的键,并将它们的含 义作为值存储在词汇表中。
  • 以整洁的方式打印每个术语及其含义。为此,可先打印术语,在它后面加 上一个冒号,再打印其含义;也可在一行打印术语,再使用换行符(\n ) 插入一个空行,然后在下一行以缩进的方式打印其含义
programming_glossary = {
    'variable': 'A placeholder for storing data.',
    'function': 'A block of organized, reusable code.',
    'loop': 'A programming construct that repeats a block of code.',
    'list': 'A collection of items in a particular order.',
    'dictionary': 'A collection of key-value pairs.'
}

print("\nProgramming Glossary:")
for term, definition in programming_glossary.items():
    print(f"{term}: {definition}\n")

6.3

练习6-4:词汇表2  现在你知道了如何遍历字典,可以整理为完成练习6-3而 编写的代码,将其中的一系列函数调用print() 替换为一个遍历字典中键和值 的循环。确定该循环正确无误后,再在词汇表中添加5个Python术语。当你再次 运行这个程序时,这些新术语及其含义将自动包含在输出中。

programming_glossary = {
    'variable': 'A placeholder for storing data.',
    'function': 'A block of organized, reusable code.',
    'loop': 'A programming construct that repeats a block of code.',
    'list': 'A collection of items in a particular order.',
    'dictionary': 'A collection of key-value pairs.'
}

print("Programming Glossary:")
for term, definition in programming_glossary.items():
    print(f"{term}: {definition}\n")

# 添加新术语
programming_glossary['tuple'] = 'A collection of ordered and immutable elements.'
programming_glossary['set'] = 'An unordered collection of unique elements.'
programming_glossary['string'] = 'A sequence of characters.'
programming_glossary['integer'] = 'A whole number.'
programming_glossary['float'] = 'A number with a decimal point.'

print("\nUpdated Programming Glossary:")
for term, definition in programming_glossary.items():
    print(f"{term}: {definition}\n")

练习6-5:河流  创建一个字典,在其中存储三条重要河流及其流经的国家。 例如,一个键值对可能是'nile': 'egypt' 。

  • 使用循环为每条河流打印一条消息,下面是一个例子。

The Nile runs through Egypt.

  • 使用循环将该字典中每条河流的名字打印出来。
  • 用循环将该字典包含的每个国家的名字打印出来。
rivers = {
    'nile': 'egypt',
    'amazon': 'brazil',
    'yangtze': 'china'
}

print("River Countries:")
for river, country in rivers.items():
    print(f"The {river.title()} runs through {country.title()}.")

print("\nRiver Names:")
for river in rivers.keys():
    print(river.title())

print("\nCountries:")
for country in rivers.values():
    print(country.title())

练习6-6:调查  在6.3.1节编写的程序favorite_languages.py中执行以下操 作。

  • 创建一个应该会接受调查的人员名单,其中有些人已包含在字典中,而其 他人未包含在字典中。
  • 遍历这个人员名单。对于已参与调查的人,打印一条消息表示感谢;对于 还未参与调查的人,打印一条消息邀请他参加。
favorite_languages = {
    'alice': 'python',
    'bob': 'java',
    'charlie': 'c++',
    'david': 'python',
    'eva': 'javascript'
}

survey_list = ['alice', 'bob', 'charlie', 'david', 'eva', 'frank']

for person in survey_list:
    if person in favorite_languages.keys():
        print(f"Thank you, {person.title()}, for participating in the survey!")
    else:
        print(f"Hello, {person.title()}, we invite you to take our survey!")

 6.4

练习6-7:人们  在为完成练习6-1而编写的程序中,再创建两个表示人的字 典,然后将这三个字典都存储在一个名为people 的列表中。遍历这个列表, 将其中每个人的所有信息都打印出来。

person1 = {
    'first_name': 'John',
    'last_name': 'Doe',
    'age': 30,
    'city': 'New York'
}

person2 = {
    'first_name': 'Alice',
    'last_name': 'Smith',
    'age': 25,
    'city': 'Los Angeles'
}

person3 = {
    'first_name': 'Bob',
    'last_name': 'Johnson',
    'age': 35,
    'city': 'Chicago'
}

people = [person1, person2, person3]

for person in people:
    print(f"First Name: {person['first_name']}")
    print(f"Last Name: {person['last_name']}")
    print(f"Age: {person['age']}")
    print(f"City: {person['city']}\n")

 

练习6-8:宠物  创建多个表示宠物的字典,每个字典都包含宠物的类型及其 主人的名字。将这些字典存储在一个名为pets 的列表中,再遍历该列表,并 将有关每个宠物的所有信息都打印出来。

pet1 = {
    'type': 'dog',
    'owner': 'Alice'
}

pet2 = {
    'type': 'cat',
    'owner': 'Bob'
}

pet3 = {
    'type': 'rabbit',
    'owner': 'Charlie'
}

pets = [pet1, pet2, pet3]

for pet in pets:
    print(f"{pet['owner'].title()} has a {pet['type']} as a pet.")

练习6-9:喜欢的地方  创建一个名为favorite_places 的字典。在这个字 典中,将三个人的名字用作键,并存储每个人喜欢的1~3个地方。为了让这个 练习更有趣些,可以让一些朋友说出他们喜欢的几个地方。遍历这个字典,并 将其中每个人的名字及其喜欢的地方打印出来。

favorite_places = {
    'John': ['Paris', 'Tokyo', 'Sydney'],
    'Alice': ['New York', 'London'],
    'Bob': ['Rome']
}

for person, places in favorite_places.items():
    print(f"{person}'s favorite places are:")
    for place in places:
        print(f"- {place}")
    print()

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

favorite_numbers = {
    'John': [7, 11, 15],
    'Alice': [3, 8, 12],
    'Bob': [5, 9]
}

for person, numbers in favorite_numbers.items():
    print(f"{person}'s favorite numbers are:")
    for number in numbers:
        print(f"- {number}")
    print()

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

cities = {
    'New York': {
        'country': 'United States',
        'population': '8.4 million',
        'fact': 'New York City is the largest city in the United States.'
    },
    'London': {
        'country': 'United Kingdom',
        'population': '8.9 million',
        'fact': 'London is the capital city of England.'
    },
    'Tokyo': {
        'country': 'Japan',
        'population': '9.7 million',
        'fact': 'Tokyo is the capital and largest city of Japan.'
    }
}

for city, info in cities.items():
    print(f"{city}:")
    print(f"  Country: {info['country']}")
    print(f"  Population: {info['population']}")
    print(f"  Fact: {info['fact']}\n")

练习6-12:扩展  本章的示例足够复杂,能以很多方式进行扩展。请对本章的 一个示例进行扩展:添加键和值、调整程序要解决的问题或改进输出的格式。

  • 在练习6-11的基础上,可以扩展城市字典,添加更多城市的信息,如气候、著名景点等。
  • 另外,可以将城市信息存储到外部文件中,通过读取文件的方式加载城市信息,使程序更加灵活和易于维护。
  • 还可以为城市信息添加交互功能,允许用户输入城市名称,然后显示该城市的信息。
# 在练习6-11的基础上,可以扩展城市字典,添加更多城市的信息,如气候、著名景点等。
# 另外,可以将城市信息存储到外部文件中,通过读取文件的方式加载城市信息,使程序更加灵活和易于维护。
# 还可以为城市信息添加交互功能,允许用户输入城市名称,然后显示该城市的信息。

# 示例代码如下:
cities = {
    'New York': {
        'country': 'United States',
        'population': '8.4 million',
        'fact': 'New York City is the largest city in the United States.'
    },
    'London': {
        'country': 'United Kingdom',
        'population': '8.9 million',
        'fact': 'London is the capital city of England.'
    },
    'Tokyo': {
        'country': 'Japan',
        'population': '9.7 million',
        'fact': 'Tokyo is the capital and largest city of Japan.'
    }
}

for city, info in cities.items():
    print(f"{city}:")
    print(f"  Country: {info['country']}")
    print(f"  Population: {info['population']}")
    print(f"  Fact: {info['fact']}\n")

  • 22
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值