Python代码:
#Chapter 4 by szh 2018.3.14 print("\n4.1") pizzas = ['New Orleans', 'Cheese Lover', 'Black Pepper Beef', 'Sausage Bite'] for pizza in pizzas: print(pizza) for pizza in pizzas: print("I like " + pizza + "pizza!") print("I really love pizza.") print("\n4.2") animals = ['dog', 'cat', 'rabbit'] for animal in animals: print(animal) for animal in animals: print("A " + animal + " would make a great pet") print("Any of these animals would make a great pet!") print("\n4.3") for i in range(1, 21): print(i) print("\n4.4") nums = list(range(1, 1000001)) for i in range(30): print(nums[i]) print("...") print("\n4.5") print(min(nums)) print(max(nums)) print(sum(nums)) print("\n4.6") nums = list(range(1, 21, 2)) for num in nums: print(num) print("\n4.7") nums = list(range(3, 31, 3)) for num in nums: print(num) print("\n4.8") nums = [] for i in range(1, 11): nums.append(i ** 3) for num in nums: print(num) print("\n4.9") nums = [i**3 for i in range(1,11)] for num in nums: print(num) print("\n4.10") print("The first three items in the list are:") print(nums[0:3]) print("Three items from the middle of the list are:") print(nums[3:6]) print("The last three items in the list are:") print(nums[-3:]) print("\n4.11") friend_pizzas = pizzas[:] pizzas.append('Popcorn Chicken') friend_pizzas.append('Super Supreme') print("My favorite pizzas are:") print(pizzas) print("My friend's favorite pizzas are:") print(friend_pizzas) print("\n4.13") foods = ('pizza', 'lobster', 'sandwich', 'peanut', 'brandy') for food in foods: print(food) print("\nafter change:") foods = ('pizza', 'lobster', 'sandwich', 'tea', 'bonbon') for food in foods: print(food)
输出结果:
4.1 New Orleans Cheese Lover Black Pepper Beef Sausage Bite I like New Orleanspizza! I like Cheese Loverpizza! I like Black Pepper Beefpizza! I like Sausage Bitepizza! I really love pizza. 4.2 dog cat rabbit A dog would make a great pet A cat would make a great pet A rabbit would make a great pet Any of these animals would make a great pet! 4.3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 4.4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ... 4.5 1 1000000 500000500000 4.6 1 3 5 7 9 11 13 15 17 19 4.7 3 6 9 12 15 18 21 24 27 30 4.8 1 8 27 64 125 216 343 512 729 1000 4.9 1 8 27 64 125 216 343 512 729 1000 4.10 The first three items in the list are: [1, 8, 27] Three items from the middle of the list are: [64, 125, 216] The last three items in the list are: [512, 729, 1000] 4.11 My favorite pizzas are: ['New Orleans', 'Cheese Lover', 'Black Pepper Beef', 'Sausage Bite', 'Popcorn Chicken'] My friend's favorite pizzas are: ['New Orleans', 'Cheese Lover', 'Black Pepper Beef', 'Sausage Bite', 'Super Supreme'] 4.13 pizza lobster sandwich peanut brandy after change: pizza lobster sandwich tea bonbon