Python 從入門到實踐 第四次課後習題

4-1 比薩 :想出至少三種你喜歡的比薩,將其名稱存儲在一個列表中,再使用for 循環將每種比薩的名稱都打印出來。 修改這個for 循環,使其打印包含比薩名稱的句子,而不僅僅是比薩的名稱。對於每種比薩,都顯示一行輸出,如“I like pepperoni pizza”。 在程序末尾添加一行代碼,它不在for 循環中,指出你有多喜歡比薩。輸出應包含針對每種比薩的消息,還有一個總結性句子,如“I really love pizza!”。

Pizza = ["Banana","Beef","Orange","Apple"]
for i in Pizza:
#     print( "I like {} pizza ! ".format(i))
      print( "I like %s pizza ! "%i)
print("I really love pizza !")    
I like Banana pizza ! 
I like Beef pizza ! 
I like Orange pizza ! 
I like Apple pizza ! 
I really love pizza !

4-2 動物 :想出至少三種有共同特徵的動物,將這些動物的名稱存儲在一個列表中,再使用for 循環將每種動物的名稱都打印出來。 修改這個程序,使其針對每種動物都打印一個句子,如“Adogwould makea great pet”。 在程序末尾添加一行代碼,指出這些動物的共同之處,如打印諸如“Any oftheseanimals would makea great pet!”這樣的句子。

Anamial = ["Panda","Pig","cat","mouse"]
for i in Anamial:
    print("A {} would make a great pet !".format(i))
print("Any of these animals would makea great pet!")
A Panda would make a great pet !
A Pig would make a great pet !
A cat would make a great pet !
A mouse would make a great pet !
Any of these animals would makea great pet!

4-3 數到20 :使用一個for 循環打印數字1~20(含)。

for i in range(1,21):
    print(i,end=" ")
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 

4-5 計算1~1 000 000的總和 :創建一個列表,其中包含數字1~1 000 000,再使用min() 和max() 覈實該列表確實是從1開始,到1 000 000結束的。另外,對這個列表 調用函數sum() ,看看Python將一百萬個數字相加需要多長時間。

lis = []
for i in range(1,1000000):
    lis.append(i)
a=min(lis)
b=max(lis)
c=sum(lis)
print(a,b,c)
1 999999 499999500000

4-6 奇數 :通過給函數range() 指定第三個參數來創建一個列表,其中包含1~20的奇數;再使用一個for 循環將這些數字都打印出來。

number = []
for i in range(1,21,2):#range(1,21,2)從1 開始生成列表,到20結束(包含20),步長爲2
    number.append(i)
for n in number:
    print(n,end=" ")
print(number)
print(min(number))
print(max(number))
print(sum(number))
number.reverse()
print(number)
1 3 5 7 9 11 13 15 17 19 [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
1
19
100
[19, 17, 15, 13, 11, 9, 7, 5, 3, 1]
number = list(range(1, 21, 2))
print(number)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

4-7 3的倍數 :創建一個列表,其中包含3~30內能被3整除的數字;再使用一個for 循環將這個列表中的數字都打印出來。

number =[]
for i in range(3,30):
    if i%3==0:
        number.append(i)
for n in number:
    print(n,end=" ")
print(number)
print(min(number))
print(max(number))
print(sum(number))
number.reverse()
print(number)
3 6 9 12 15 18 21 24 27 [3, 6, 9, 12, 15, 18, 21, 24, 27]
3
27
135
[27, 24, 21, 18, 15, 12, 9, 6, 3]
numbers = list(range(3,31,3))
for num in numbers:
	print(num,end=" ")
3 6 9 12 15 18 21 24 27 30 

4-8 立方 :將同一個數字乘三次稱爲立方。例如,在Python中,2的立方用2**3 表示。請創建一個列表,其中包含前10個整數(即1~10)的立方,再使用一個for 循 環將這些立方數都打印出來。

number = [n**3 for n in range(1,11)] #在這個示例中,for 循環爲for n in range(1,11) ,它將值 1~10提供給表達式n**3。
for i in number:
    print(i, end=" ")
print(number)
number =  list(range(1,11))
for i in [n**3 for n in number]:
    print(i,end=" ")
1 8 27 64 125 216 343 512 729 1000 

4-9 立方解析 :使用列表解析生成一個列表,其中包含前10個整數的立方。

number = [n**3 for n in range(1,11)] #在這個示例中,for 循環爲for n in range(1,11) ,它將值 1~10提供給表達式n**3。
for i in number:
    print(i, end=" ")
print(number)
1 8 27 64 125 216 343 512 729 1000 [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

4-10 切片 :選擇你在本章編寫的一個程序,在末尾添加幾行代碼,以完成如下任務。
打印消息“Thefirst threeitems in thelistare:”,再使用切片來打印列表的前三個元素。
打印消息“Threeitems fromthe middle ofthelistare:”,再使用切片來打印列表中間的三個元素。
打印消息“Thelast threeitems in thelistare:”,再使用切片來打印列表末尾的三個元素。

Fruit = ["蘋果","梨","橘子","火龍果","banana","Orange"]
print("Thefirst threeitems in thelistare:" + Fruit[:3])
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-10-72c4c4e0e528> in <module>
      1 Fruit = ["蘋果","梨","橘子","火龍果","banana","Orange"]
----> 2 print("Thefirst threeitems in thelistare:" + Fruit[:3])


TypeError: can only concatenate str (not "list") to str
zifu = "Things"
print("Thefirst threeitems in thelistare:" + zifu[:3])
print("Threeitems fromthe middle ofthelistare:" + zifu[2:5] )
print("Thelast threeitems in thelistare:" + zifu[-3:])
print("Thelast threeitems in thelistare:" + zifu[-1:-4:-1])
Thefirst threeitems in thelistare:Thi
Threeitems fromthe middle ofthelistare:ing
Thelast threeitems in thelistare:ngs
Thelast threeitems in thelistare:sgn
my_foods = ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
print("The first three items in the list are:")
print(my_foods[:3])  # 4-10-1
print("\nThree items from the middle of the list are:")
print(my_foods[1:4])  # 4-10-2
print("\nThree items from the middle of the list are:")
print(my_foods[-3:])  # 4-10-3
The first three items in the list are:
['pizza', 'falafel', 'carrot cake']

Three items from the middle of the list are:
['falafel', 'carrot cake', 'cannoli']

Three items from the middle of the list are:
['carrot cake', 'cannoli', 'ice cream']

4-11 你的比薩和我的比薩 :在你爲完成練習4-1而編寫的程序中,創建比薩列表的副本,並將其存儲到變量friend_pizzas 中,再完成如下任務。
在原來的比薩列表中添加一種比薩。 在列表friend_pizzas 中添加另一種比薩。 覈實你有兩個不同的列表。爲此,打印消息“My favorite pizzasare:”,再使用一個for 循環來打印第一個列表;打印消息“My friend’s favorite pizzasare:”,再使用一 個for 循環來打印第二個列表。覈實新增的比薩被添加到了正確的列表中。

my_foods = ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
friend_pizzas = my_foods[:]
my_foods.append('cheese')  # 4-11-1
friend_pizzas.append('seafood')  # 4-11-2
for i in my_foods:
	print("My favorite pizzas are: " + i)
for i in friend_pizzas:
	print("My friend’s favorite pizzas are: " + i)
My favorite pizzas are: pizza
My favorite pizzas are: falafel
My favorite pizzas are: carrot cake
My favorite pizzas are: cannoli
My favorite pizzas are: ice cream
My favorite pizzas are: cheese
My friend’s favorite pizzas are: pizza
My friend’s favorite pizzas are: falafel
My friend’s favorite pizzas are: carrot cake
My friend’s favorite pizzas are: cannoli
My friend’s favorite pizzas are: ice cream
My friend’s favorite pizzas are: seafood
my_foods = ["水果","牛肉","海魚","大閘蟹","核桃"]
friend_pizzas = my_foods[:]
#要複製列表,可創建一個包含整個列表的切片,方法是同時省略起始索引和終止索引([:] )。這讓Python創建一個始於第一個元素,終止於最後一個元素的切片,即複製整個 列表。
my_foods.append('雞肉')  
friend_pizzas.append('豬肉') 
for i in my_foods:
	print("My favorite pizzas are: " + i)
for i in friend_pizzas:
	print("My friend’s favorite pizzas are: " + i)
print(my_foods[1:4]) 

4-13 自助餐 :有一家自助式餐館,只提供五種簡單的食品。請想出五種簡單的食品,並將其存儲在一個元組中。 使用一個for 循環將該餐館提供的五種食品都打印出來。 嘗試修改其中的一個元素,覈實Python確實會拒絕你這樣做。 餐館調整了菜單,替換了它提供的其中兩種食品。請編寫一個這樣的代碼塊:給元組變量賦值,並使用一個for 循環將新元組的每個元素都打印出來。

HlepDinner = ("烤金針菇","骨肉相連","羊肉串","牛肉麪","水果沙拉")
print(HlepDinner)
HlepDinner[0]="宮保雞丁"
('烤金針菇', '骨肉相連', '羊肉串', '牛肉麪', '水果沙拉')



---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-5-165bfccac886> in <module>
      1 HlepDinner = ("烤金針菇","骨肉相連","羊肉串","牛肉麪","水果沙拉")
      2 print(HlepDinner)
----> 3 HlepDinner[0]="宮保雞丁"


TypeError: 'tuple' object does not support item assignment
HlepDinner = ("烤金針菇","骨肉相連",["烤青椒","冰淇淋","毛血旺"],"羊肉串","牛肉麪","水果沙拉")
print(HlepDinner)
print(type(HlepDinner))
for i in HlepDinner:
    print(i,end=" ")
('烤金針菇', '骨肉相連', ['烤青椒', '冰淇淋', '毛血旺'], '羊肉串', '牛肉麪', '水果沙拉')
<class 'tuple'>
烤金針菇 骨肉相連 ['烤青椒', '冰淇淋', '毛血旺'] 羊肉串 牛肉麪 水果沙拉 
HlepDinner = ("烤金針菇","骨肉相連","羊肉串","牛肉麪","水果沙拉")
HlepDinner = ("烤金針菇","骨肉相連",["烤青椒","冰淇淋","毛血旺"],"羊肉串","牛肉麪","水果沙拉")
print(HlepDinner)
print(HlepDinner[-1:-5:-1])
HlepDinner =HlepDinner[-1:-5:-1] + ("烤紅薯","涮肚","薯片")
print(HlepDinner)
('烤金針菇', '骨肉相連', ['烤青椒', '冰淇淋', '毛血旺'], '羊肉串', '牛肉麪', '水果沙拉')
('水果沙拉', '牛肉麪', '羊肉串', ['烤青椒', '冰淇淋', '毛血旺'])
('水果沙拉', '牛肉麪', '羊肉串', ['烤青椒', '冰淇淋', '毛血旺'], '烤紅薯', '涮肚', '薯片')
發佈了4 篇原創文章 · 獲贊 3 · 訪問量 357
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章