第四章python作業

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

>>> pets=['Dog','Cat','Rabbit']
>>> for pet in pets:
	print(pet)

	
Dog
Cat
Rabbit
>>> for pet in pets:
	print('A '+pet+' would make a great pet')

	
A Dog would make a great pet
A Cat would make a great pet
A Rabbit would make a great pet
>>> print('Any of these animals would make a great pet')
Any of these animals would make a great pet
>>> 

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

>>> for i in range(1,21):
	print(i)	
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將一百萬個數字相加需要多長時間。

>>> a=list(range(1,1000001))
>>> print(min(a))
1
>>> print(max(a))
1000000
>>> print(sum(a))
500000500000

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

>>> for i in range(1,21,2):
        print(i)	  
1
3
5
7
9
11
13
15
17
19

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

>>> a=list(range(3,31,3))
>>> for i in a:
	print(i)
3
6
9
12
15
18
21
24
27
30

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

>>> cube=[i**3 for i in range(1,11)]
>>> for num in cube:
	print(num)	
1
8
27
64
125
216
343
512
729
100
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:”,再使用切片來打印列表末尾的三個元素。

>>> cube=[i**3 for i in range(1,11)]
>>> print(cube[:3])
[1, 8, 27]
>>> print('The first three items in the list are: ',cube[:3])
The first three items in the list are:  [1, 8, 27]
>>> print('The middle three items in the list are: ',cube[4:7])
The middle three items in the list are:  [125, 216, 343]
>>> print('The last three items in the list are: ',cube[-3:])
The last three items in the list are:  [512, 729, 1000]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章