Python编程 从入门到实践 练习3-4~3-7

本文通过一个晚餐邀请的例子,展示了Python中列表的基本操作,包括创建、修改、插入、删除和遍历元素,以及如何处理列表长度变化的情况。

3-4 嘉宾名单

guest_list = ['alice', 'bob', 'carmen', ]
print(guest_list[0].title() + ',please come and have dinner with me.')
print(guest_list[1].title() + ',please come and have dinner with me.')
print(guest_list[2].title() + ',please come and have dinner with me.')

3-4输出

3-5 修改嘉宾名单

#修改嘉宾名单
guest_list = ['alice', 'bob', 'carmen', ]
unable_guest = guest_list.pop(1)
new_guest = 'beer'
guest_list.insert(1,new_guest)
print(guest_list[0].title() + ',please come and have dinner with me.')
print(guest_list[1].title() + ',please come and have dinner with me.')
print(guest_list[2].title() + ',please come and have dinner with me.')
print(unable_guest.title() + ' unable to attend.')

3-5输出

3-6 添加嘉宾

#修改嘉宾名单
#添加嘉宾
guests = ['alice', 'bob', 'carmen', ]
unable_guest = guests.pop(1)
new_guest = 'beer'
guests.insert(1,new_guest)
guests.insert(0,'david')
guests.insert(2,'Eric')
guests.append('ford')
print(guests[0].title() + ',please come and have dinner with me.')
print(guests[1].title() + ',please come and have dinner with me.')
print(guests[2].title() + ',please come and have dinner with me.')
print(guests[3].title() + ',please come and have dinner with me.')
print(guests[4].title() + ',please come and have dinner with me.')
print(guests[5].title() + ',please come and have dinner with me.')
print(unable_guest.title() + ' unable to attend.')
print('I find a bigger table.')

3-6输出

3-7 缩减名单

#修改嘉宾名单
#添加嘉宾
#缩减名单
guests = ['alice', 'bob', 'carmen', ]
unable_guest = guests.pop(1)
new_guest = 'beer'
guests.insert(1,new_guest)
guests.insert(0,'david')
guests.insert(2,'Eric')
guests.append('ford')
print(guests[0].title() + ',please come and have dinner with me.')
print(guests[1].title() + ',please come and have dinner with me.')
print(guests[2].title() + ',please come and have dinner with me.')
print(unable_guest.title() + ' unable to attend.')
print('I find a bigger table.')
print(guests[3].title() + ',please come and have dinner with me.')
print(guests[4].title() + ',please come and have dinner with me.')
print(guests[5].title() + ',please come and have dinner with me.')
print(guests.pop().title() + ",sorry can't invite you to dinner.")
print(guests.pop().title() + ",sorry can't invite you to dinner.")
print(guests.pop().title() + ",sorry can't invite you to dinner.")
print(guests.pop().title() + ",sorry can't invite you to dinner.")
print(guests[0].title() + ' is still invited.')
print(guests[1].title() + ' is still invited.')
print('I can only invite two guests to come and have dinner with me.')
del guests[1]
del guests[0]
print(guests)

3-7输出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值