4-2 动物 :想出至少三种有共同特征的动物,将这些动物的名称存储在一个列表中,再使用for 循环将每种动物的名称都打印出来。 修改这个程序,使其针对每种动物都打印一个句子,如“A dog would make a great pet”。 在程序末尾添加一行代码,指出这些动物的共同之处,如打印诸如“Any of these animals would make a great pet!”这样的句子。
源代码
animals = ["dog","cat","sheep"] for animal in animals: print("A "+animal+" can't fly.") print("All these animals can't fly.")
输出结果
4-6 奇数 :通过给函数range() 指定第三个参数来创建一个列表,其中包含1~20的奇数;再使用一个for 循环将这些数字都打印出来。
源代码
numbers = range(1,21,2) for num in numbers: print(num)
输出结果
4-8 立方 :将同一个数字乘三次称为立方。例如,在Python中,2的立方用2**3 表示。请创建一个列表,其中包含前10个整数(即1~10)的立方,再使用一个for 循 环将这些立方数都打印出来
源代码
cube = [value **3 for value in range(1,11) ] for num in cube: print(num)
输出结果
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:”,再使用切片来打印列表末尾的三个元素。
源代码
message = "abcdefghi" print ("The first three items in the list are:"+ message[0:3]) print ("Three items in the middle of the list are:"+ message[3:6]) print ("The last three items in the list are:"+ message[6:9])
输出结果