首页 > 代码库 > python练习题1

python练习题1

需求:

控制台根据用户选择实现:

     1、添加用户(个别信息必填)add user

     2、展示用户列表 list user

     3、根据名字搜索用户信息 search user

     4、根据名字修改用户信息 modify user

     5、退出 exit

listinfo=[]def add_user():    print "Please fill in according to the prompt information:"    choise="y"        while choise==‘y‘:        dictinfo={}        name=raw_input("name*:")        if name=="":            name=raw_input("name cannot be empty:")        age=raw_input("age:")        sex=raw_input("sex:")        iph=raw_input("iphone*:")        if iph=="":            iph=raw_input("iph cannot be empty:")                dictinfo[‘name‘]=name        dictinfo[‘age‘]=age        dictinfo[‘sex‘]=sex        dictinfo[‘iph‘]=iph        listinfo.append(dictinfo)         print listinfo        choise=raw_input("go on? y/n:")    make_choice()           return listinfodef list_user(listinfo):    print "The following information for all users"    i=1    for dictinfo in listinfo:        print "*"*15        print "%s user:"% i        print "name is %s\nage is %s\nsex is %s\niph is %s" % (dictinfo[‘name‘],dictinfo[‘age‘],dictinfo[‘sex‘],dictinfo[‘iph‘])                i+=1    make_choice()def search_user(listinfo):    name=raw_input("Please enter the name of you want to search:")    for dictinfo in listinfo:        if dictinfo[‘name‘]==name:            print "name is %s\nage is %s\nsex is %s\niph is %s" % (dictinfo[‘name‘],dictinfo[‘age‘],dictinfo[‘sex‘],dictinfo[‘iph‘])        else:            continue    make_choice()def modify_user(listinfo):    name=raw_input("Who do you want to modify the information:")    i=0    for dictinfo in listinfo:        if dictinfo[‘name‘]==name:            print dictinfo            modione=raw_input("what do you want to modify:")            dictinfo[modione]=raw_input("new content:")            listinfo[i]=dictinfo            print "sucess"                i+=1    print listinfo    make_choice()        def make_choice():    print"\n"    print "make a choice 1:add user,2:list user,3:search user,4:modify user,5,exit!"    print "\n"    choice=raw_input("please make a choice:")    if choice=="1":        add_user()    elif choice == "2":        list_user(listinfo)    elif choice=="3":        search_user(listinfo)    elif choice=="4":        modify_user(listinfo)    elif choice=="5":        print‘DONE!‘        exit()    else:        print "please enter a number between 1-5:"          listinfo=add_user()  

 

遇到的问题,看下图:

 技术分享

开始把字典的定义放在了while循环外层,这样,每次往list中添加一个新字典,就会使得之前添加的字典值全部更改为新的值

问题原因,放在外层,列表中添加的字典引用的全是同一个对象,一旦字典值进行了变化,其他字典也跟着变化

解决方法,把字典的定义放在while里面,每次创建一个字典都是不同的对象,就不会更改之前的字典的值

 

python练习题1