Week Two Assignment

第三章习题

3-1

将朋友姓名存储在列表中,依次将其打印

names = ['Yan Bin' 'Wang Yongfeng', 'Wu Ziyang']
for name in names:
    print(name)

3-2

为3-1中的朋友打印问候语.抬头位相应朋友的姓名

# use names in 3-1
for name in names:
    print("hello {}, nice to meet you!".format(name))

3-4/ 3-5/

创建一个列表,包含3位你想邀请的人,使用这个列表打印消息,邀请这些人与你共进晚餐.

invitationList = [
    'Benson Yan',
    'Walker Wang',
    'Ziyang Wu'
]

def invite(invitationList):
    for name in invitationList:
        print('hello {}, I\'d like to have dinner with you!'
            .format(name))

invite(invitationList)

你得知一位朋友无法参与聚会.在程序末尾添加一条print语句,指出谁无法参与聚会.

print('{} is not available!'.format(invitationList[1]))

修改嘉宾名单,将无法赴约的嘉宾修改为其他嘉宾

invitationList[1] = 'Mengmeng Yan'

再次打印一条消息,向名单中的嘉宾发出邀请.

invite(invitationList)

3-6

你刚得到更大的餐桌,思考你想多邀请哪3个人. 以3-4/3-5为基础,增加一条print语句,指出你有一个更大的餐桌

print('I got a bigger table!')

使用insert将一个嘉宾加入邀请列表

invitationList.insert(0, 'Wu Zhongen')

第四章

4-3 至 4-9

# 4-3
for i in range(1, 21):
    print(i)
# 4-4
ls = [i for i in range(1, 1000000+1)]
for i in ls:
    print(i)
# 4-5
# using 4-4
print(min(ls))
print(max(ls))
print(sum(ls))
# 4-6
ls = [i for i in range(1, 21, 2)]
for i in ls:
    print(i)
# 4-7(3)
ls = [i for i in range(3, 31) if i % 3 == 0]
for i in ls:
    print(i)
# 4-8
ls = [i ** 3 for i in range(1, 11)]
for i in ls:
    print(i)
# 4-10
ls = [i for i in range(10)]
print(ls[:3])
print(ls[-3:])
print(ls[3:6])
# 4 - 13
foods = 'banana', 'apple', 'orange', 'pinapple', 'noddle'
for food in foods:
    print(food)

foods[0] = 'bad banana'
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: 'tuple' object does not support item assignment