与小卡特一起学python 第12章 收集起来,列表与字典 动手试一试

#12 列表和字典 动手试一试

#12-1 写一个程序,让用户提供5个名字,程序把名字保存在一个列表中,并打印出来
#方法1比较笨,用输入形式。代码比较多。
print("Enter 5 names:")
name=[]
name1=input()
name2=input()
name3=input()
name4=input()
name5=input()
name=(name1,name2,name3,name4,name5)
print("The names are"," ",end='')
for name6 in name:
    print(name6," ",end="")

#方法2 使用循环输入
nameList = []
print("Enter 5 names:")
for i in range(5):
    name=input()
    nameList.append(name)
##print("The names are ",nameList) #由于名字引号,我修改如下,去掉引号,得题目一样结果。
print("The names are","",end=" ")
for namelist in nameList: #增加一个变量namelist
    print(namelist," ",end='')

#12-2修改题目1,显示原来列表,并还要显示排序后的列表
nameList = []
print("Enter 5 names:")
for i in range(5):
    name=input()
    nameList.append(name)
newlist = nameList[:]
newlist.sort()
print(nameList)
print(newlist)

#12-3 修改题目1,显示用户输入的第三个名字
nameList = []
print("Enter 5 names:")
for i in range(5):
    name = input()
    nameList.append(name)
print("The third name you entered is: ", nameList[2])

12-4 修改第1题,让用户替换其中一个名字。用户应该能选择要替换哪个名字,然后键入新名字。
最后显示新的列表
nameList = []
print("Enter 5 names:")
for i in range(5):
    name=input()
    nameList.append(name)
No=int (input("Replace one name.Which one?(1-4)"))
nameList[No-1] = input("New name:")
print(nameList)
#12-5 编写一个字典
diction = {}
while 1:
    command =input("'a' to add word,'l' to lookup a word,'q' to quit")

    if command == "a":
        word = input("Type the word:")
        definition = input("Type the definition:")
        diction[word] = definition
        print("Word added")
    if command == "l":
       word = input ("type the word:")
       if word in diction.keys():
          print (diction[word])
       else:
          print("That word isn't in the dictionary yet.")
    if command =="q":
       break

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/220205/viewspace-2075111/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/220205/viewspace-2075111/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值