《python编程从入门到实践》第2版 第三章课后练习

第三章

练习3-1: 姓名 将一些朋友的姓名存储在一个列表中,并将其命名为names 。依次访问该列表中的每个元素,从而将每个朋友的姓名打印出来。

names = ['xiaoming','xiaohong','xiaobai','xiaohei']
print(names[0])
print(names[1])
print(names[2])
print(names[3])

输出:

xiaoming
xiaohong
xiaobai
xiaohei

练习3-2: 问候语 继续使用练习3-1中的列表,但不打印每个朋友的姓名,而为每人打印一条消息。每条消息都包含相同的问候语,但抬头为相应朋友的姓名。

names = ['xiaoming','xiaohong','xiaobai','xiaohei']
msg = f"{names[0].title()}, nice to meet you!"
print(msg)

msg = f"{names[1].title()}, nice to meet you!"
print(msg)

msg = f"{names[2].title()}, nice to meet you!"
print(msg)

msg = f"{names[3].title()}, nice to meet you!"
print(msg)

输出:

Xiaoming, nice to meet you!
Xiaohong, nice to meet you!
Xiaobai, nice to meet you!
Xiaohei, nice to meet you!

练习3-3: 自己的列表 想想你喜欢的通勤方式,如骑摩托车或开汽车,并创建一个包含多种通勤方式的列表。根据该列表打印一系列有关这些通勤方式的宣言,下面是一个例子。I would like to own a Honda motorcycle.

commutes = ['walk','bicycle','bus','ship','airplane']
msg = f"I would like to travel around the world by {commutes[0].title()}"
print(msg)
msg = f"I would like to travel around the world by {commutes[1].title()}"
print(msg)
msg = f"I would like to travel around the world by {commutes[2].title()}"
print(msg)
msg = f"I would like to travel around the world by {commutes[3].title()}"
print(msg)
msg = f"I would like to travel around the world by {commutes[4].title()}"
print(msg)

输出:

I would like to travel around the world by Walk
I would like to travel around the world by Bicycle
I would like to travel around the world by Bus
I would like to travel around the world by Ship
I would like to travel around the world by Airplane

练习3-4: 嘉宾名单 如果你可以邀请任何人一起共进晚餐(无论是在世的还是故去的),你会邀请哪些人?请创建一个列表,其中包含至少三个你想邀请的人,然后使用这个列表打印消息,邀请这些人来与你共进晚餐。

guests = ['guido van rossum', 'jack turner', 'lynn hill']
name = guests[0].title()
print(f"{name}, please come to dinner.")
name = guests[1].title()
print(f"{name}, please come to dinner.")
name = guests[2].title()
print(f"{name}, please come to dinner.")

输出:

Guido Van Rossum, please come to dinner.
Jack Turner, please come to dinner.
Lynn Hill, please come to dinner.

练习3-5: 修改嘉宾名单 你刚得知有位嘉宾无法赴约,因此需要另外邀请一位嘉宾。

  • 以完成练习3-4时编写的程序为基础,在程序末尾添加一条print 语句,指出哪位嘉宾无法赴约。
  • 修改嘉宾名单,将无法赴约的嘉宾的姓名替换为新邀请的嘉宾的姓名。
  • 再次打印一系列消息,向名单中的每位嘉宾发出邀请。
guests = ['guido van rossum', 'jack turner', 'lynn hill']

name = guests[0].title()
print(f"{name}, please come to dinner.")
name = guests[1].title()
print(f"{name}, please come to dinner.")
name = guests[2].title()
print(f"{name}, please come to dinner.")

name = guests[0].title()
print(f"\nSorry, {name} can't make it to dinner.")
# Guido 无法赴约,转而邀请 Gary。
guests[0] = 'gary snyder'
# 重新打印邀请函。
name = guests[0].title()
print(f"\n{name}, please come to dinner.")
name = guests[1].title()
print(f"{name}, please come to dinner.")
name = guests[2].title()
print(f"{name}, please come to dinner.")

输出:

Guido Van Rossum, please come to dinner.
Jack Turner, please come to dinner.
Lynn Hill, please come to dinner.

Sorry, Guido Van Rossum can't make it to dinner.

Gary Snyder, please come to dinner.
Jack Turner, please come to dinner.
Lynn Hill, please come to dinner.

练习3-6: 添加嘉宾 你刚找到了一个更大的餐桌,可容纳更多的嘉宾。请想想你还想邀请哪三位嘉宾。

  • 以完成练习3-4或练习3-5时编写的程序为基础,在程序末尾添加一条print 语句,指出你找到了一个更大的餐桌。
  • 使用insert() 将一位新嘉宾添加到名单开头。
  • 使用insert() 将另一位新嘉宾添加到名单中间。
  • 使用append() 将最后一位新嘉宾添加到名单末尾。
  • 打印一系列消息,向名单中的每位嘉宾发出邀请。
guests = ['guido van rossum', 'jack turner', 'lynn hill']

name = guests[0].title()
print(f"{name}, please come to dinner.")
name = guests[1].title()
print(f"{name}, please come to dinner.")
name = guests[2].title()
print(f"{name}, please come to dinner.")

name = guests[0].title()
print(f"\nSorry, {name} can't make it to dinner.")
# Guido 无法赴约,转而邀请 Gary。
guests[0] = 'gary snyder'
# 重新打印邀请函。
name = guests[0].title()
print(f"\n{name}, please come to dinner.")
name = guests[1].title()
print(f"{name}, please come to dinner.")
name = guests[2].title()
print(f"{name}, please come to dinner.")

# 找到了更大的餐桌,再邀请一些嘉宾。
guests.insert(0, 'frida kahlo')
guests.insert(2, 'reinhold messner')
guests.append('elizabeth peratrovich')
name = guests[0].title()
print(f"\n{name}, please come to dinner.")
name = guests[1].title()
print(f"{name}, please come to dinner.")
name = guests[2].title()
print(f"{name}, please come to dinner.")
name = guests[3].title()
print(f"{name}, please come to dinner.")
name = guests[4].title()
print(f"{name}, please come to dinner.")
name = guests[5].title()
print(f"{name}, please come to dinner.")

输出:

Guido Van Rossum, please come to dinner.
Jack Turner, please come to dinner.
Lynn Hill, please come to dinner.

Sorry, Guido Van Rossum can't make it to dinner.

Gary Snyder, please come to dinner.
Jack Turner, please come to dinner.
Lynn Hill, please come to dinner.

Frida Kahlo, please come to dinner.
Gary Snyder, please come to dinner.
Reinhold Messner, please come to dinner.
Jack Turner, please come to dinner.
Lynn Hill, please come to dinner.
Elizabeth Peratrovich, please come to dinner.

练习3-7: 缩减名单 你刚得知新购买的餐桌无法及时送达,因此只能邀请两位嘉宾。

  • 以完成练习3-6时编写的程序为基础,在程序末尾添加一行代码,打印一条你只能邀请两位嘉宾共进晚餐的消息。
  • 使用pop() 不断地删除名单中的嘉宾,直到只有两位嘉宾为止。每次从名单中弹出一位嘉宾时,都打印一条消息,让该嘉宾知悉你很抱歉,无法邀请他来共进晚餐。
  • 对于余下两位嘉宾中的每一位,都打印一条消息,指出他依然在受邀人之列。
  • 使用del 将最后两位嘉宾从名单中删除,让名单变成空的。打印该名单,核实程序结束时名单确实是空的。
guests = ['guido van rossum', 'jack turner', 'lynn hill']

name = guests[0].title()
print(f"{name}, please come to dinner.")
name = guests[1].title()
print(f"{name}, please come to dinner.")
name = guests[2].title()
print(f"{name}, please come to dinner.")

name = guests[0].title()
print(f"\nSorry, {name} can't make it to dinner.")
# Guido 无法赴约,转而邀请 Gary。
guests[0] = 'gary snyder'
# 重新打印邀请函。
name = guests[0].title()
print(f"\n{name}, please come to dinner.")
name = guests[1].title()
print(f"{name}, please come to dinner.")
name = guests[2].title()
print(f"{name}, please come to dinner.")

# 找到了更大的餐桌,再邀请一些嘉宾。
guests.insert(0, 'frida kahlo')
guests.insert(2, 'reinhold messner')
guests.append('elizabeth peratrovich')
name = guests[0].title()
print(f"\n{name}, please come to dinner.")
name = guests[1].title()
print(f"{name}, please come to dinner.")
name = guests[2].title()
print(f"{name}, please come to dinner.")
name = guests[3].title()
print(f"{name}, please come to dinner.")
name = guests[4].title()
print(f"{name}, please come to dinner.")
name = guests[5].title()
print(f"{name}, please come to dinner.")

# 糟糕,餐桌无法及时送达!
print("\nSorry, we can only invite two people to dinner.")
name = guests.pop()
print(f"Sorry, {name.title()} there's no room at the table.")
name = guests.pop()
print(f"Sorry, {name.title()} there's no room at the table.")
name = guests.pop()
print(f"Sorry, {name.title()} there's no room at the table.")
name = guests.pop()
print(f"Sorry, {name.title()} there's no room at the table.")
# 应该只剩下两位嘉宾了,向他们发出邀请。
name = guests[0].title()
print(f"{name}, please come to dinner.")
name = guests[1].title()
print(f"{name}, please come to dinner.")
# 清空名单。
del(guests[0])
del(guests[0])
# 核实名单是空的。
print(guests)

输出:

Guido Van Rossum, please come to dinner.
Jack Turner, please come to dinner.
Lynn Hill, please come to dinner.

Sorry, Guido Van Rossum can't make it to dinner.

Gary Snyder, please come to dinner.
Jack Turner, please come to dinner.
Lynn Hill, please come to dinner.

Frida Kahlo, please come to dinner.
Gary Snyder, please come to dinner.
Reinhold Messner, please come to dinner.
Jack Turner, please come to dinner.
Lynn Hill, please come to dinner.
Elizabeth Peratrovich, please come to dinner.

Sorry, we can only invite two people to dinner.
Sorry, Elizabeth Peratrovich there's no room at the table.
Sorry, Lynn Hill there's no room at the table.
Sorry, Jack Turner there's no room at the table.
Sorry, Reinhold Messner there's no room at the table.
Frida Kahlo, please come to dinner.
Gary Snyder, please come to dinner.
[]

练习3-8: 放眼世界 想出至少5个你渴望去旅游的地方。
将这些地方存储在一个列表中,并确保其中的元素不是按字母顺序排列的。
按原始排列顺序打印该列表。不要考虑输出是否整洁的问题,只管打印原始Python列表。

  • 使用sorted() 按字母顺序打印这个列表,同时不要修改它。
  • 再次打印该列表,核实排列顺序未变。
  • 使用sorted() 按与字母顺序相反的顺序打印这个列表,同时不要修改它。
  • 再次打印该列表,核实排列顺序未变。
  • 使用reverse() 修改列表元素的排列顺序。打印该列表,核实排列顺序确实变了。
    使用reverse() 再次修改列表元素的排列顺序。打印该列表,核实已恢复到原来的排列顺序。
  • 使用sort() 修改该列表,使其元素按字母顺序排列。打印该列表,核实排列顺序确实变了。
  • 使用sort() 修改该列表,使其元素按与字母顺序相反的顺序排列。打印该列表,核实排列顺序确实变了。
locations = ['lhasa', 'yunnan', 'xinjiang', 'chengdu', 'beijing']
print("Original order:")
print(locations)
print("\nAlphabetical:")
print(sorted(locations))
print("\nOriginal order:")
print(locations)
print("\nReverse alphabetical:")
print(sorted(locations, reverse=True))
print("\nOriginal order:")
print(locations)
print("\nReversed:")
locations.reverse()
print(locations)
print("\nOriginal order:")
locations.reverse()
print(locations)
print("\nAlphabetical")
locations.sort()
print(locations)
print("\nReverse alphabetical")
locations.sort(reverse=True)
print(locations)

输出:

Original order:
['lhasa', 'yunnan', 'xinjiang', 'chengdu', 'beijing']

Alphabetical:
['beijing', 'chengdu', 'lhasa', 'xinjiang', 'yunnan']

Original order:
['lhasa', 'yunnan', 'xinjiang', 'chengdu', 'beijing']

Reverse alphabetical:
['yunnan', 'xinjiang', 'lhasa', 'chengdu', 'beijing']

Original order:
['lhasa', 'yunnan', 'xinjiang', 'chengdu', 'beijing']

Reversed:
['beijing', 'chengdu', 'xinjiang', 'yunnan', 'lhasa']

Original order:
['lhasa', 'yunnan', 'xinjiang', 'chengdu', 'beijing']

Alphabetical
['beijing', 'chengdu', 'lhasa', 'xinjiang', 'yunnan']

Reverse alphabetical
['yunnan', 'xinjiang', 'lhasa', 'chengdu', 'beijing']

练习3-9: 晚餐嘉宾 在完成练习3-4~练习3-7时编写的程序之一中,使用len() 打印一条消息,指出你邀请了多少位嘉宾来共进晚餐。

guests = ['guido van rossum', 'jack turner', 'lynn hill']
len = len(guests)
print(f"I invited {len} guests to dinner.")

输出:

I invited 3 guests to dinner.

练习3-10: 尝试使用各个函数 想想可存储到列表中的东西,如山川、河流、国家、城市、语言或你喜欢的任何东西。
编写一个程序,在其中创建一个包含这些元素的列表,然后,对于本章介绍的每个函数,都至少使用一次来处理这个列表。

languages = ['Chinese', 'French', 'English']
print(f"The length of languages is {len(languages)}.")
languages.append('Spanish')
print(f"Original languages: {languages}.")
languages.insert(1,'Arabic')
languages.insert(3,'Cantonese')
print(f"Inserted languages: {languages}.")
print(f"Pop up element: {languages.pop()}.")
print(f"Pop up languages: {languages}.")
del languages[2]
print(f"Deleted languages: {languages}.")
languages[2] = 'Portuguese'
print(f"Modified languages: {languages}.")
print(f"Sorted languages: {sorted(languages)}.")
print(f"Original languages: {languages}.")
languages.sort()
print(f"Sort languages: {sorted(languages)}.")
languages.reverse()
print(f"Reversed languages: {sorted(languages)}.")
languages.reverse()
print(f"Original languages: {languages}.")

输出:

The length of languages is 3.
Original languages: ['Chinese', 'French', 'English', 'Spanish'].
Inserted languages: ['Chinese', 'Arabic', 'French', 'Cantonese', 'English', 'Spanish'].
Pop up element: Spanish.
Pop up languages: ['Chinese', 'Arabic', 'French', 'Cantonese', 'English'].
Deleted languages: ['Chinese', 'Arabic', 'Cantonese', 'English'].
Modified languages: ['Chinese', 'Arabic', 'Portuguese', 'English'].
Sorted languages: ['Arabic', 'Chinese', 'English', 'Portuguese'].
Original languages: ['Chinese', 'Arabic', 'Portuguese', 'English'].
Sort languages: ['Arabic', 'Chinese', 'English', 'Portuguese'].
Reversed languages: ['Arabic', 'Chinese', 'English', 'Portuguese'].
Original languages: ['Arabic', 'Chinese', 'English', 'Portuguese'].

练习3-11: 有意引发错误 如果你还没有在程序中遇到过索引错误,就尝试引发一个这种错误。在你的一个程序中,修改其中的索引,以引发索引错误。关闭程序前,务必消除这个错误。

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles[-1])
print(motorcycles[3])
motorcycles = []
print(motorcycles[-1])

输出:

suzuki
Traceback (most recent call last):
  File "C:\Users\86150\PycharmProjects\python_work\3-11 error.py", line 5, in <module>
    print(motorcycles[3])
IndexError: list index out of range
Traceback (most recent call last):
  File "C:\Users\86150\PycharmProjects\python_work\3-11 error.py", line 7, in <module>
    print(motorcycles[-1])
IndexError: list index out of range

修改:

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles[-1])
print(motorcycles[2])
motorcycles = ['nihao']
print(motorcycles[-1])

输出:

suzuki
suzuki
nihao

你可能感兴趣的:(python,开发语言)