《Python编程:从入门到实践》第四章练习题

这个博客介绍了《Python编程:从入门到实践》第四章的多个练习,包括使用for循环打印比萨、动物名称、数字序列,计算数字总和,处理奇数和倍数,立方运算,列表切片,以及对比萨和食物的个人喜好。此外,还涉及到列表和元组的操作,如复制、添加元素和修改。练习旨在巩固Python的基础语法和列表操作技巧。

《Python编程:从入门到实践》第四章练习题

4-1 比萨

想出至少三种你喜欢的比萨,将其名称存储在一个列表中,再使用 for 循环将每种比萨的名称都打印出来。

  • 修改这个for 循环,使其打印包含比萨名称的句子,而不仅仅是比萨的名称。对于每种比萨,都显示一行输出,如“I like pepperoni pizza”。
  • 在程序末尾添加一行代码,它不在for 循环中,指出你有多喜欢比萨。输出应包含针对每种比萨的消息,还有一个总结性句子,如“I really love pizza!”。

代码:

pizzas = ['romano', 'ricotta', 'pepperoni']
for pizza in pizzas:
    print("I like " + pizza + " pizza")

print("I really love pizza!")

4-2 动物

想出至少三种有共同特征的动物,将这些动物的名称存储在一个列表中,再使用for 循环将每种动物的名称都打印出来。

  • 修改这个程序,使其针对每种动物都打印一个句子,如“Adogwould makea great pet”。
  • 在程序末尾添加一行代码,指出这些动物的共同之处,如打印诸如“Any of these animals would makea great pet!”这样的句子。

代码:

animals = ['cat', 'dog', 'rabbit', 'bird']
for animal in animals:
    print("A " + animal + " would make a great pet")

print("Any of these animals would make a great pet!")

4-3 数到20

使用一个for 循环打印数字1~20(含)。

代码:

for i in range(1, 21):
    print(i)

4-4 一百万

创建一个列表,其中包含数字1~1 000 000,再使用一个for 循环将这些数字打印出来(如果输出的时间太长,按Ctrl+ C停止输出,或关闭输出窗口)。

代码:

list = [value for value in range(1, 10 ** 6 + 1)]
for i in list:
    print(i)

4-5 计算1~1 000 000的总和

创建一个列表,其中包含数字1~1 000 000,再使用min() 和max() 核实该列表确实是从1开始,到1 000 000结束的。另外,对这个列表
调用函数sum() ,看看Python将一百万个数字相加需要多长时间。

代码:

list = [value for value in range(1, 10**6+1)]
print("min of list: " + str(min(list)) +"\nmax of list: " + str(max(list)))
print("sum of list: " + str(sum(list)))

4-6 奇数

通过给函数 range() 指定第三个参数来创建一个列表,其中包含1~20的奇数;再使用一个for 循环将这些数字都打印出来。

代码:

list = [odd for odd in range(1, 20, 2)]
for i in list:
    print(i)

4-7 3的倍数

创建一个列表,其中包含3~30内能被3整除的数字;再使用一个for 循环将这个列表中的数字都打印出来。

代码:

number = []
for i in range(3, 31):
    if i % 3 == 0:
        number.append(i)
# print(number)
for i in number:
    print(i)

4-8 立方

将同一个数字乘三次称为立方。例如,在Python中,2的立方用2**3 表示。请创建一个列表,其中包含前10个整数(即1~10)的立方,再使用一个 for 循环将这些立方数都打印出来。

代码:

values = []
for i in range(1, 11):
    values.append(i ** 3)
# print(values)
for value in values:
    print(value)

4-9 立方解析

使用列表解析生成一个列表,其中包含前10个整数的立方。

代码:

# 使用列表解析的方法
values = [value ** 3 for value in range(1, 11)]
for value in values:
    print(value)

4-10 切片

选择你在本章编写的一个程序,在末尾添加几行代码,以完成如下任务。

  • 打印消息“The first three items in the list are:”,再使用切片来打印列表的前三个元素。
  • 打印消息“Three items from the middle of the list are:”,再使用切片来打印列表中间的三个元素。
  • 打印消息“The last three items in the list are:”,再使用切片来打印列表末尾的三个元素。
values = [value ** 3 for value in range(1, 11)]
print("The first three items in the list are:")
print(values[:3])
print("Three items from the middle of the list are:")
print(values[4:7])
print("The last three items in the list are:")
print(values[-3:])

4-11 你的披萨和我的披萨

在你为完成练习4-1而编写的程序中,创建比萨列表的副本,并将其存储到变量friend_pizzas 中,再完成如下任务。

  • 在原来的比萨列表中添加一种比萨。
  • 在列表 friend_pizzas 中添加另一种比萨。
  • 核实你有两个不同的列表。为此,打印消息“My favorite pizzasare:”,再使用一个for 循环来打印第一个列表;打印消息“My friend’s favorite pizzasare:”,再使用一个 for 循环来打印第二个列表。核实新增的比萨被添加到了正确的列表中。

代码:

pizzas = ['romano', 'ricotta', 'pepperoni']
friend_pizzas = pizzas[:]

pizzas.append('fruit')
friend_pizzas.append('meet')

print("My favorite pizzas are:")
for pizza in pizzas:
    print(pizza + " ")

print("My friend's favorite pizzas are:")
for pizza in friend_pizzas:
    print(pizza + " ")
print("\n")

4-12 使用多个循环

在本节中,为节省篇幅,程序 foods.py 的每个版本都没有使用 for 循环来打印列表。请选择一个版本的 foods.py,在其中编写两个 for 循环,将各个食品列表都打印出来。

代码:

my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]

print("My favorite foods are:")
for food in my_foods:
    print(food)

print("\nMy friend's favorite foods are:")
for food in friend_foods:
    print(food)

4-13 自助餐

有一家自助式餐馆,只提供五种简单的食品。请想出五种简单的食品,并将其存储在一个元组中。

  • 使用一个for 循环将该餐馆提供的五种食品都打印出来。
  • 尝试修改其中的一个元素,核实Python确实会拒绝你这样做。
  • 餐馆调整了菜单,替换了它提供的其中两种食品。请编写一个这样的代码块:给元组变量赋值,并使用一个for 循环将新元组的每个元素都打印出来。
foods = ('rice', 'egg', 'fish', 'beef', 'apple')
print("Original menu:")
for food in foods:
    print(food)

# foods[-1] = 'orange'

'''报错信息
Traceback (most recent call last):
  File "C:/Users/81228/Documents/Program/Python Program/chapter4/4-13_buffet.py", line 5, in <module>
    foods[-1] = 'orange'
TypeError: 'tuple' object does not support item assignment
'''

print("\nModified menu:")
foods = ('rice', 'egg', 'fish', 'milk', 'orange')
for food in foods:
    print(food)

4-14 PEP 8

略。

4-15 代码审核

略。

Python编程:从入门实践》是一本适合编程初学者的书籍,书中包含大量练习题以帮助读者巩固所学知识。以下是一些章节的练习题答案示例: ### 第2章:变量和简单数据类型 ```python # 2-1 message = "hello" print(message) # 2-2 message = "nihao1" print(message) message = "nihao2" print(message) # 2-3 name = "lihua" print("Hello " + name + ", would you like to learn some Python today") # 2-4 name = "hua Li" print(name + "\n" + name.title() + "\n" + name.upper() + "\n" + name.lower()) # 2-5 print(&#39;Albert Einstein once said, "A person who never made a mistake never tried anything new"&#39;) # 2-6 famous_person = "Albert Einstein" message = &#39;"A person who never made a mistake never tried anything new"&#39; print(famous_person + " once said," + message) # 2-7 person = "\tli hua\t" print(person + person.rstrip() + person.lstrip() + person.strip()) # 2-8 print(5 + 3) print(10 - 2) print(2 * 4) print(16 / 2) # 2-9 number = 7 print("I like " + str(number)) # 2-10 # 向大家问好 print("hello") # 2-11 import this ``` ### 第3章:列表简介 ```python # 3-1 friends = [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;] for friend in friends: print(friend) # 3-2 friends = [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;] for friend in friends: print("Hello " + friend + ", how are you?") # 3-4 guests = [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;] for guest in guests: print("Dear " + guest + ", you are invited to dinner.") # 3-5 guests = [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;] unavailable_guest = &#39;Bob&#39; new_guest = &#39;David&#39; guests.remove(unavailable_guest) guests.append(new_guest) for guest in guests: print("Dear " + guest + ", you are invited to dinner.") # 3-6 guests = [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;] new_guests = [&#39;David&#39;, &#39;Eve&#39;, &#39;Frank&#39;] guests.insert(0, new_guests[0]) guests.insert(len(guests) // 2, new_guests[1]) guests.extend(new_guests[2:]) for guest in guests: print("Dear " + guest + ", you are invited to dinner.") ``` ###4章:操作列表 ```python # 4-1 pizzas = [&#39;Pepperoni&#39;, &#39;Cheese&#39;, &#39;Veggie&#39;] for pizza in pizzas: print("I like " + pizza + " pizza.") print("I really love pizza!") # 4-2 animals = [&#39;Dog&#39;, &#39;Cat&#39;, &#39;Bird&#39;] for animal in animals: print("A " + animal + " would make a great pet.") print("Any of these animals would make a great pet!") # 4-3 for number in range(1, 21): print(number) # 4-4 for number in range(1, 1000001): print(number) # 4-5 numbers = list(range(1, 1000001)) print(min(numbers)) print(max(numbers)) print(sum(numbers)) # 4-6 for number in range(1, 21, 2): print(number) # 4-7 for number in range(3, 31, 3): print(number) # 4-8 cubes = [number ** 3 for number in range(1, 11)] for cube in cubes: print(cube) # 4-9 cubes = [number ** 3 for number in range(1, 11)] print(cubes) # 4-10 pizzas = [&#39;Pepperoni&#39;, &#39;Cheese&#39;, &#39;Veggie&#39;, &#39;Hawaiian&#39;, &#39;BBQ&#39;] print("The first three items in the list are: " + str(pizzas[:3])) print("Three items from the middle of the list are: " + str(pizzas[1:4])) print("The last three items in the list are: " + str(pizzas[-3:])) # 4-11 my_pizzas = [&#39;Pepperoni&#39;, &#39;Cheese&#39;, &#39;Veggie&#39;] friend_pizzas = my_pizzas[:] my_pizzas.append(&#39;Hawaiian&#39;) friend_pizzas.append(&#39;BBQ&#39;) print("My favorite pizzas are: " + str(my_pizzas)) print("My friend&#39;s favorite pizzas are: " + str(friend_pizzas)) ``` 这些示例涵盖了书中部分章节的练习题答案,可以帮助读者更好地理解和掌握Python编程的基础知识。希望这些内容对你有所帮助[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UestcXiye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值