Python编程:从入门到实践的动手试一试答案(第四章)

#4-1 比萨
pizzas = ['apple pizza','banana pizza','chili pizza']
for pizza in pizzas:
    print('I like ' + pizza.title())
print('\nI really love pizza!')
#4-2 动物
animals = ['dog','cat','horse']
for animal in animals:
    print('A ' + animal + ' would make a great pet')
print('\nAny of these animals would make a great pet!')
#4-3 数到20
for x in range(1,21):
    print(x)
#4-4 一百万
numbers = []
for x in range(1,1000001):
    numbers.append(x)
for number in numbers:
    print(number)
#4-5 计算1~1 000 000的总和
numbers = []
for x in range(1,1000001):
    numbers.append(x)
print(min(numbers))
print(max(numbers))
print(sum(numbers))
#4-6 奇数
numbers = []
for x in range(1,20,2):
    numbers.append(x)
for number in numbers:
    print(number)
#4-7 3的倍数
numbers = []
for x in range(3,31,3):
    numbers.append(x)
for number in numbers:
    print(number)
#4-8 立方
numbers = []
for x in range(1,11):
    numbers.append(x**3)

for number in numbers:
    print(number)
#4-9 立方解析
numbers = [x**3 for x in range(1,11)]
for number in numbers:
    print(number)
#4-10 切片
numbers = [x**3 for x in range(1,11)]
for number in numbers:
    print(number)

print('The first three items in the list are:')
print(numbers[0:3])
print('Three items from the middle of the list are:')
print(numbers[3:6])
print('The last three items in the list are:')
print(numbers[-3:])
#4-11 你的比萨和我的比萨
pizzas = ['apple pizza','banana pizza','chili pizza']
for pizza in pizzas:
    print('I like ' + pizza.title())
print('\nI really love pizza!')

friend_pizzas = pizzas[:]
pizzas.append('milk pizza')
friend_pizzas.append('black pizza')

print('\nMy favorite pizzas are:')
for pizza in pizzas:
    print(pizza)
print("\nMy friend's favorite pizzas are:")
for pizza in friend_pizzas:
    print(pizza)  
#4-12 使用多个循环
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]

my_foods.append('cannoli')
friend_foods.append('ice cream')

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 自助餐
foods = ('pizza', 'falafel', 'carrot cake','apple','banana')
for food in foods:
    print(food)

foods = ('pizza', 'beef', 'milk','apple','banana')
for food in foods:
    print(food)

你可能感兴趣的:(Python编程:从入门到实践的动手试一试答案(第四章))