1. 程式人生 > >(第二週作業:3、4章)有關列表的練習

(第二週作業:3、4章)有關列表的練習

3-1 姓名:將一些朋友的名字儲存到一個列表中,命名為names,再依次打印出來

names = ['Mary', 'Mike', 'Tom', 'Jerry']
for name in names:
    print(name)

可以看到,執行程式碼後出現瞭如下文字:

Mary
Mike
Tom
Jerry

3-2 問候語:列表與3-1相同,但是不只列印姓名,而是為每人列印一條問候語

names = ['Mary', 'Mike', 'Tom', 'Jerry']
for name in names:
    print(name + ", How are you?")
可以看到,執行程式碼後出現瞭如下文字:
Mary, How are you?
Mike, How are you?
Tom, How are you?
Jerry, How are you?

3-4 嘉賓名單:

list = ['Hitler', 'Stalin', 'Tom']
for name in list:
    print(name + ", I'd like to invate you for a dinner.")
可以看到,執行程式碼後出現瞭如下文字:
Hitler, I'd like to invate you for a dinner.
Stalin, I'd like to invate you for a dinner.
Tom, I'd like to invate you for a dinner.

3-5 修改嘉賓名單:

list = ['Hitler', 'Stalin', 'Tom']
for name in list:
    print(name + ", I'd like to invate you for a dinner.")
absence = 'Tom'
print(absence + " could not come.")
list.remove(absence)
list.append("Jerry") 
for name in list:
    print(name + ", I'd like to invate you for a dinner.")
可以看到,執行程式碼後出現瞭如下文字:
Hitler, I'd like to invate you for a dinner.
Stalin, I'd like to invate you for a dinner.
Tom, I'd like to invate you for a dinner.
Tom could not come.
Hitler, I'd like to invate you for a dinner.
Stalin, I'd like to invate you for a dinner.
Jerry, I'd like to invate you for a dinner.
3-6 新增嘉賓:

list = ['Hitler', 'Stalin', 'Tom']
for name in list:
    print(name + ", I'd like to invate you for a dinner.")
print("I find a bigger table")
list.insert(0, "Jerry")
list.insert(2, "John")
list.append("Mary")
for name in list:
    print(name + ", I'd like to invate you for a dinner.")
可以看到,執行程式碼後出現瞭如下文字:
Hitler, I'd like to invate you for a dinner.
Stalin, I'd like to invate you for a dinner.
Tom, I'd like to invate you for a dinner.
I find a bigger table
Jerry, I'd like to invate you for a dinner.
Hitler, I'd like to invate you for a dinner.
John, I'd like to invate you for a dinner.
Stalin, I'd like to invate you for a dinner.
Tom, I'd like to invate you for a dinner.
Mary, I'd like to invate you for a dinner.


4-3 數到20

for x in range(1, 21):
    print(x)

可以看到,程式執行後列印了1到20的整數

4-4 一百萬

for x in range(1, 1000001):
    print(x)
可以看到,程式執行後列印了1到一百萬的整數

4-5 計算一到一百萬的總和

sum = 0
for x in range(1, 1000001):
    sum += x
print(sum)

計算結果

500000500000

4-6 奇數

list = [x for x in range(1, 21, 2)]
for x in list:
    print(x)
可以看到,執行程式碼後出現瞭如下文字:
1
3
5
7
9
11
13
15
17
19

4-8 立方

list = [x**3 for x in range(1, 11)]
for x in list:
    print(x)
可以看到,執行程式碼後出現瞭如下文字:
1
8
27
64
125
216
343
512
729
1000