最近在自学 Python,看的教材是《Python编程:从入门到实践》第二版(Python Crash Course 2 nd Edition:A Hands-On, Project-Based Introduction to Programming)这本书。作者译者都很棒,非常适合初学编程者,里面提供的很多建议都非常实用。
(对应书中3.2节后的动手试一试,以下主要为我做题后的心得笔记)
该题目主要是熟系一下3.2节中提到的列表概念以及列表的增删改,比较基础没什么问题,我贴一下自己写的代码。
#author:早知晓
#last runtime:2021\07\20
invitees=['eric','susan','john','amy']
print(f"{invitees[0]},do you have time to eat dinner with me this Sunday?")
print(f"{invitees[1]},do you have time to eat dinner with me this Sunday?")
print(f"{invitees[2]},do you have time to eat dinner with me this Sunday?")
print(f"{invitees[3]},do you have time to eat dinner with me this Sunday?\n")
print(f"{invitees[1]} can't eat dinner with me~\n")
invitees=['eric','jim','john','amy']
print(f"{invitees[0]},do you have time to eat dinner with me this Sunday?")
print(f"{invitees[1]},do you have time to eat dinner with me this Sunday?")
print(f"{invitees[2]},do you have time to eat dinner with me this Sunday?")
print(f"{invitees[3]},do you have time to eat dinner with me this Sunday?")
print("Now i find a bigger table to eat dinner~\n")
invitees.insert(0,'jwj')
invitees.insert(3,'fy')
invitees.append('zt')
print(f"{invitees[0]},do you have time to eat dinner with me this Sunday?")
print(f"{invitees[1]},do you have time to eat dinner with me this Sunday?")
print(f"{invitees[2]},do you have time to eat dinner with me this Sunday?")
print(f"{invitees[3]},do you have time to eat dinner with me this Sunday?")
print(f"{invitees[4]},do you have time to eat dinner with me this Sunday?")
print(f"{invitees[5]},do you have time to eat dinner with me this Sunday?")
print(f"{invitees[6]},do you have time to eat dinner with me this Sunday?\n")
print("Sorry,because my table can't reach in time so that i only can invite two friends to eat dinner.\n")
invitee=invitees.pop()
print(f"Sorry,invitee,i can't eat dinner with you.")
invitee=invitees.pop()
print(f"Sorry,invitee,i can't eat dinner with you.")
invitee=invitees.pop()
print(f"Sorry,invitee,i can't eat dinner with you.")
invitee=invitees.pop()
print(f"Sorry,invitee,i can't eat dinner with you.")
invitee=invitees.pop()
print(f"Sorry,invitee,i can't eat dinner with you.\n")
print(f"Dear {invitees[0]},you can eat dinner with me!")
print(f"Dear {invitees[1]},you can eat dinner with me!\n")
del invitees[1]
del invitees[0]
print(invitees)
其中有一个值得注意的地方就是最后一题:使用 del 将最后两位嘉宾从名单中删除,让名单变成空的。
我开始写的代码是下面这样的,然后运行就报错了。
del invitees[0]
del invitees[1]
看了一下报错信息我又返回看了看代码,原来是因为当解释器执行 del invitees[0] 以后,invitees 列表中就只剩一个数据了,此时解释器再执行 del invitees[1] 就会找不到索引为 1 的数据,同时从报错信息也可以看出出错原因是列表元素索引超出范围了。修改代码为如下所示即可运行成功。
del invitees[1]
del invitees[0]
运行结果如下图:
如果各位小伙伴有什么问题或者建议,欢迎大家评论区交流呀~
希望大家都走在开满鲜花的路上,加油鸭~
版权说明
原文作者:早知晓
博文链接:Click here
转载请注明出处,谢谢合作~