Write an address book code in python

Source: Internet
Author: User

Write an address book code in python

Reference knowledge

  • List + dict: used to temporarily store user data

  • CPickle is used to access formatted files.

  • Still use file for file storage

Solve the Problem 1. Start to do it

Original code implementation function (can be used as a template)

1. Check whether the input content is in the given menu directory. If yes, the corresponding result is returned. If no input content exists, an error is returned.

2. Call the exit function of the OS module.

3. Combine dictionaries with loops and add functions to implement the switch function

#! /Usr/bin/envpython # coding: utf8 # Author: zhuima # Date: 2015-03-22 # Version: 0.1 # Function: displayalistandadddate # import module importosdefmenu (): ''' sets the munu directory, operation Interface ''' print ''' 1. adduserinfo2.dispalluserinfo3. updateuserinfobyusername4: deluserbyusername5: sortuserinfoby0.exitprogram '''op = raw_input ('pleaseselectone >>') returnopdeft_exit (): '''exit the program ''' OS. _ exit (0) deftxl_error (): ''' when the user output option is not included in the defined option, the error '''printprint' Unko is returned. Nwoptions, Pleasetryagain! '# Define dict. Use the function to implement the switch function ops ={# '1': txl_add, # '2': txl_dis, # '3': txl_update, #'4 ': txl_del, # '5': txl_sort, '0': txl_exit,} defmain (): ''' main program ''' whileTrue: op = menu () ops. get (op, txl_error) () if _ name __= = '_ main _': main ()
2. Add a user

Ideas

An empty list is defined by default, and dict is nested to implement the temporary storage function.

  • 1. Added code

    # Import module importostxl = []... deftxl_add (): ''' Add User ''' name = raw_input ('pleaseenteryourname >>> ') age = raw_input ('pleaseenteryourage >>> ') gender = raw_input ('pleaseenteryourgender >>> ') tel = raw_input ('pleaseenteryourtel >>>') txl. append ({'name': name, 'age': age, 'gender': gender, 'tel': tel}) deftxl_disp (): '''display the original txl list ''' printtxl ..... ops = {'1': txl_add, '2': txl_disp, # '3': txl_update, # '4': txl_del, # '5': txl_sort, '0 ': txl_exit ,}
  • 2. Test Results

    [root@mysql01day0330]#pythonv2_1.py1.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>2[]1.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>1PleaseEnterYourName>>>zhuimaPleaseEnterYourAge>>>28PleaseEnterYourGender>>>fPleaseEnterYourTel>>>100861.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>2[{'gender':'f','age':'28','tel':'10086','name':'zhuima'}]1.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>0
  • 3. complete code block

3. format the output

Format the output and use the dictionary.

Formatted output: print "% (name) s \ t % (age) s" % dict

  • 1. Add code snippets

    Deftxl_disp (): ''' display the original txl list ''' print "name \ tage \ tgender \ ttel" print "---------------------" forxintxl: print "% (name) s \ t % (age) s \ t % (gender) s \ t % (tel) s "% x
  • 2. Test Results

    [root@mysql01day0330]#pythonv2_1.py1.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>2nameagegendertel----------------------------1.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>2nameagegendertel----------------------------1.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>1PleaseEnterYourName>>>zhuimaPleaseEnterYourAge>>>28PleaseEnterYourGender>>>fPleaseEnterYourTel>>>100861.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>1PleaseEnterYourName>>>nickPleaseEnterYourAge>>>25PleaseEnterYourGender>>>mPleaseEnterYourTel>>>100101.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>1PleaseEnterYourName>>>kalePleaseEnterYourAge>>>33PleaseEnterYourGender>>>fPleaseEnterYourTel>>>100111.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>2nameagegendertel----------------------------zhuima28f10086nick25m10010kale33f100111.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>0
  • 3. complete code

4. File writing and reading

Ideas:

The cPickle concept is introduced. cPickle reads and stores files in a format operation,

CPickle's loads function (read files from files to ensure the original format) and dumps (store object files in related formats)

  • 1. Add a code block

    # Import module importosimpcpcpickle # define the database file name fname = 'Contact. db 'txl = []... deftxl_add (): ''' Add User '''.... # Call the txl_save () module txl_save () deftxl_disp (): ''' the original txl list is displayed and adjusted twice. If txl is empty, the printed wood has a file, if txl is not empty, the data information ''' iflen (txl)> 0: print "name \ tage \ tgender \ ttel" print '------------------------ 'forxintxl: print "% (name) s \ t % (age) s \ t % (gender) s \ t % (tel) s" % xelse: printprint ">>> Thisisaemptyfile, thereisnoinfomation! >>> "Deftxl_save (): ''' use cPickle to convert the list to a string and then write it to the file ''' = cPickle. dumps (txl) fp = file (fname, 'w') fp. write (s) fp. close () deftxl_load (): ''' read information from the file, and then use cPickle to convert string to list ''' ifos. path. exists (fname): fp = file (fname) s = fp. read () fp. close () txl. extend (cPickle. loads (s ))
  • 2. Write test results

    [root@mysql01day0330]#lstest.pyv2_1.pyv2.py[root@mysql01day0330]#pythonv2_1.py1.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>2>>>Thisisaemptyfile,Thereisnoinfomation!>>>1.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>1PleaseEnterYourName>>>zhuimaPleaseEnterYourAge>>>25PleaseEnterYourGender>>>fPleaseEnterYourTel>>>100861.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>2nameagegendertel----------------------------zhuima25f100861.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>1PleaseEnterYourName>>>nickPleaseEnterYourAge>>>22PleaseEnterYourGender>>>mPleaseEnterYourTel>>>100101.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>2nameagegendertel----------------------------zhuima25f10086nick22m100101.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>0[root@mysql01day0330]#lscontact.dbtest.pyv2_1.pyv2.py
  • 3. Read test results

    [root@mysql01day0330]#pythonv2_1.py1.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>2nameagegendertel----------------------------zhuima25f10086nick22m100101.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>0[root@mysql01day0330]#
  • 4. complete code

5. delete a user

Ideas:

Delete data by user name

Let's take a look at a demonstration.

  • Case study: how to delete a nested list dictionary

    In [6]: sOut [6]: [{'age': 25, 'name': 'zhuima '}, {'age': 33, 'name ': 'Nick '}] # The first idea is to use del to delete the dictionary, but the nesting does not take effect In [7]: forxins: ifx ['name'] = 'zhuima ': delx...: prints...: [{'age': 25, 'name': 'zhuima '}, {'age': 33, 'name ': 'Nick '}] # Use remove of the List to delete it. In [10]: forxins: ifx ['name'] = 'zhuima': s. remove (x )....: In [11]: sOut [11]: [{'age': 33, 'name': 'Nick '}]
  • 1. code snippets

    Deftxl_del (): ''' deletes user information based on the user name and stores data, how to '''name = raw_input ('pleaseenteryourwanttodeletename >>> ') forlineintxl: ifline ['name'] = name: txl. remove (line) break # Remember to call the stored function at last. Otherwise, delete the function only for the current session and no file txl_save () is written ()
  • 2. Test Results

    [root@mysql01day0330]#pythonv2_1.py1.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>2nameagegendertel----------------------------zhuima25f10086nick22m100101.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>4PleaseEnterYourWantToDeletename>>>nick1.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>2nameagegendertel----------------------------zhuima25f100861.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>0[root@mysql01day0330]#pythonv2_1.py1.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>2nameagegendertel----------------------------zhuima25f100861.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>
  • 3. complete code

6. Custom sorting based on user input

Ideas:

Sort by user selection

The introduced function is lambda txl. sort (key = lambda x: x [op]).

  • 1. code snippets

    Deftxl_sort (): ''' sorts data based on user input. The lambda function is used, with bugs, you should provide a default value for sorting ''' op = raw_input ('orderby [name | age | gender | tel] Display >>> ') txl. sort (key = lambdax: x [op]) txl_disp ()
  • 2. Test Results

    [root@mysql01day0330]#pythonv2_1.py1.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>2nameagegendertel----------------------------zhuima25f10086nick22m10011kale29f10093tony18m100101.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>5OrderBy[name|age|gender|tel]Display>>>namenameagegendertel----------------------------kale29f10093nick22m10011tony18m10010zhuima25f100861.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>5OrderBy[name|age|gender|tel]Display>>>agenameagegendertel----------------------------tony18m10010nick22m10011zhuima25f10086kale29f100931.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>
  • 3. complete code

7. Update Data

Ideas:
Method 1: update with dictionary reassignment (the first method used in this case)

Method 2: locate the dict of the corresponding user based on the index, and update the entire dict.

  • Case study of finding the corresponding dict to update based on the index

    In[38]:sOut[38]:[{'age':44,'name':'zhuima'},{'age':33,'name':'nick'}]In[39]:forxins:....:ifx['name']=='zhuima':....:s[s.index(x)]={'name':'zhuima521','age':28}....:In[40]:sOut[40]:[{'age':28,'name':'zhuima521'},{'age':33,'name':'nick'}]In[41]:
  • 1. code snippets

    Deftxl_update (status = True): ''' update the user's data based on the user name. The user name cannot be changed. If the option is not updated, the default value is retained, otherwise, '''txl _ disp () name = raw_input ('selectoneupdatebyname >>> ') forlineintxl: ifline ['name'] = name: status = Falseold_age = line ['age'] old_gender = line ['gender'] old_tel = line ['tel '] age = raw_input ('pleaseenteryouragefor % s >>>>' % name) gender = raw_input ('pleaseenteryourgenderfor % s >>>' % name) tel = raw_input ('pleaseenteryourtelfor % s >>>' % name) iflen (age) = 0: line ['age'] = old_ageelse: line ['age'] = ageiflen (gender) = 0: line ['gender'] = old_genderelse: line ['gender'] = genderiflen (tel) = 0: line ['tel'] = old_telelse: line ['tel'] = telbreakifstatus: print "UnkonwUser, TryAgain! "Txl_save ()
  • 2. Test Results

    [root@mysql01day0330]#pythonv2_1.py1.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>2nameagegendertel----------------------------fuck30m90000kale33f10093tony18m10010zhuima25f10086max32f200001.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>3nameagegendertel----------------------------fuck30m90000kale33f10093tony18m10010zhuima25f10086max32f20000SelectOneUpdateByName>>>kalePleaseEnterYourAgeforkale>>>PleaseEnterYourGenderforkale>>>PleaseEnterYourTelforkale>>>999991.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>2nameagegendertel----------------------------fuck30m90000kale33f99999tony18m10010zhuima25f10086max32f200001.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>3nameagegendertel----------------------------fuck30m90000kale33f99999tony18m10010zhuima25f10086max32f20000SelectOneUpdateByName>>>minUnkonwUser,TryAgain!1.adduserinfo2.dispalluserinfo3.updateuserinfobyusername4:deluserbyusername5:sortuserinfoby0.exitprogramPleaseselectone>>>
  • 3. complete code

Summary

So far, we have used dict to complete database addition, deletion, modification, query, sorting, and other operations.

Complete code

#! /Usr/bin/envpython # coding: utf8 # Author: zhuima # Date: 2015-03-22 # Version: 0.1 # Function: displayalistandadddate # import module importosimpcpicklefname = 'Contact. db 'txl = [] defmenu (): ''' sets the munu directory and provides the user's operation interface '''print ''' 1. adduserinfo2.dispalluserinfo3. updateuserinfobyusername4: deluserbyusername5: Comment ''' op = raw_input ('pleaseselectone >>> ') returnopdeftxl_add (): ''' Add User ''' name = raw_input ('pleenteraseyourn Ame >>>') age = raw_input ('pleaseenteryourage >>>') gender = raw_input ('pleaseenteryourgender >>>') tel = raw_input ('pleaseenteryourtel >>> ') txl. append ({'name': name, 'age': age, 'gender': gender, 'tel ': tel}) txl_save () deftxl_disp (): ''' display the original txl list ''' iflen (txl)> 0: print "name \ tage \ tgender \ ttel" print '------------------------ 'forxintxl: print "% (name) s \ t % (age) s \ t % (gender) s \ t % (tel) s "% xelse: printprint" >>> thisaemptyfile, T Hereisnoinfomation! >>> "Deftxl_save (): ''' write the data, and convert the format to ''' = cPickle before writing. dumps (txl) fp = file (fname, 'w') fp. write (s) fp. close () deftxl_load (): ''' read the file. If the file exists, ''' ifos. path. exists (fname): fp = file (fname) s = fp. read () fp. close () txl. extend (cPickle. loads (s) deftxl_update (status = True): ''' update the user's data based on the user name. The user name cannot be changed. If the option is not updated, the default value is retained, otherwise, '''txl _ disp () name = raw_input ('selectoneupdatebyname >>> ') forlineintxl: ifline ['name'] = name: status = False Old_age = line ['age'] old_gender = line ['gender'] old_tel = line ['tel '] age = raw_input ('pleaseenteryouragefor % s >>>' % name) gender = raw_input ('pleaseenteryourgenderfor % s >>>' % name) tel = raw_input ('pleaseenteryourtelfor % s >>>' % name) iflen (age) = 0: line ['age'] = old_ageelse: line ['age'] = ageiflen (gender) = 0: line ['gender'] = old_genderelse: line ['gender'] = genderiflen (tel) = 0: line ['tel'] = old_telelse: line ['tel'] = telbreakifstatus: Print "UnkonwUser, TryAgain! "Txl_save () deftxl_del (): ''' Delete the user's information based on the user name, and store the data '''name = raw_input ('pleaseenteryourwanttodeletename >>') forlineintxl: ifline ['name'] = name: txl. remove (line) breaktxl_save () deftxl_sort (): ''' sort data based on user input, the lambda function '''op = raw_input ('orderby [name | age | gender | tel] Display >>> ') txl is used. sort (key = lambdax: x [op]) txl_disp () deftxl_exit (): ''' exit the program ''' OS. _ exit (0) deftxl_error (): ''' when the user output option is not included in the defined option, the error '''printprint' Unkon is returned. Woptions, Pleasetryagain! '# Define dict. Use the function to implement the switch function ops = {'1': txl_add, '2': txl_disp, '3': txl_update, '4': txl_del, '5': txl_sort, '0': txl_exit,} txl_load () defmain (): ''' main program ''' whileTrue: op = menu () ops. get (op, txl_error) () if _ name __= = '_ main _': main ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.