4-2:动物:遍历一个列表
animals = ["cat","dog","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 number in range(1,21):
print(number)
4-5:计算1~1000000的总和
numbers=list(range(1,1000001))
print(min(numbers))
print(max(numbers))
print(sum(numbers))
4-6:奇数
numbers=list(range(1,20,2))
for number in numbers:
print(number)
4-7:3的倍数
numbers=list(range(3,31,3))
for number in numbers:
print(number)
4-9:立方解析
numbers=[value**3 for value in range(1,11)]
for number in numbers:
print(number)
4-10:切片:打印一个列表不同部分的元素
numbers=[2,4,5,23,54,65,241,456,267]
print("The first three items in the list are:") #打印列表前三个元素
for number in numbers[:3]:
print(number)
print("Three items from the middle of the list are:") #打印列表中间的三个元素
for number in numbers[3:6]:
print(number)
print("The last three items in the list are:") #打印列表最后的三个元素
for number in numbers[-3:]:
print(number)
4-11 你的披萨和我的披萨:复制一个列表,并为两个列表添加不同的元素,并打印出两个不同的列表
pizzas = ["Seafood pizza","Sausage pizza","Cheese pizza"]
your_pizzas = pizzas[:]
pizzas.append("Beef pizza")
your_pizzas.append("Cron pizza")
print("My favorite pizza is:", end="")
for pizza in pizzas:
print(" "+pizza,end="")
print("\n")
print("My friends' favorite pizza is:",end="")
for pizza in your_pizzas:
print(" "+pizza,end="")
4-13:自助餐:创立一个元组,打印,并为元组重新赋值,再次打印。
foods = ("cola","humburger","fired chicken","ice-cream","coffee")
for food in foods:
print(food)
foods = ("tea","pizza","salad","ice-cream","coffee")
print("The new menu is:")
for food in foods:
print(food)