4-2 动物:想出至少三种有共同特征的动物,将这些动物的名称存储在一个列表中,再使用for 循环将每种动物的名称都打印出来。 ·修改这个程序,使其针对每种动物都打印一个句子,如“A dog would make a great pet”。 ·在程序末尾添加一行代码,指出这些动物的共同之处,如打印诸如“Any of these animals would make a great pet!”这样的句子。
animals = ['cat','dag','rabit']
for animal in animals:
print(animal)
cat
dag
rabit
animals = ['cat','dag','rabit']
for animal in animals:
print('A ' + animal + ' would make a great pet!')
A cat would make a great pet!
A dag would make a great pet!
A rabit would make a great pet!
animals = ['cat','dag','rabit']
for animal in animals:
print('A ' + animal + ' would make a great pet!')
print("Any of these animals would make a great pet!")
A cat would make a great pet!
A dag would make a great pet!
A rabit would make a great pet!
Any of these animals would make a great pet!
nums = range(3,31,3)
for num in nums:
print(num,end = ' ')
3 6 9 12 15 18 21 24 27 30
4-9 立方解析:使用列表解析生成一个列表,其中包含前10个整数的立方。
nums = [i**3 for i in range(1,11)]
for num in nums:
print(num,end = ' ')
1 8 27 64 125 216 343 512 729 1000
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:”,再使用切片来打印列表末尾的三个元素。
nums = [i**3 for i in range(1,10)]
for num in nums[:3]:
print(num,end = ' ')
print()
for num in nums[3:6]:
print(num,end = ' ')
print()
for num in nums[6:]:
print(num,end = ' ')
1 8 27
64 125 216
343 512 729
4-2 动物:想出至少三种有共同特征的动物,将这些动物的名称存储在一个列表中,再使用for 循环将每种动物的名称都打印出来。 ·修改这个程序,使其针对每种动物都打印一个句子,如“A dog would make a great pet”。 ·在程序末尾添加一行代码,指出这些动物的共同之处,如打印诸如“Any of these animals would make a great pet!”这样的句...