【python】——小程序之电话薄
初学python,写一个小程序练习一下。主要功能就是增删改查的一些功能。主要用到的技术:字典的使用,pickle的使用,io文件操作。代码如下:
1 import pickle 2 3 #studentinfo = {'netboy': '15011038018',\ 4 # 'godboy': '15011235698'} 5 studentinfo = {} 6 7 FUNC_NUM = 5 8 9 def write_file(value): 10 file = open('student_info.txt', 'wb') 11 file.truncate() 12 pickle.dump(value, file, True) 13 file.close 14 15 def read_file(): 16 global studentinfo 17 file = open('student_info.txt', 'rb') 18 studentinfo = pickle.load(file) 19 file.close() 20 21 def search_student(): 22 global studentinfo 23 name = input('please input student\'s name:') 24 if name in studentinfo: 25 print('name:%s phone:%s' % (name, studentinfo[name])) 26 else: 27 print('has no this body') 28 29 def delete_student(): 30 global studentinfo 31 name = input('please input student\'s name:') 32 if name in studentinfo: 33 studentinfo.pop(name) 34 write_file(studentinfo) 35 else: 36 print('has no this body') 37 38 def add_student(): 39 global studentinfo 40 name = input('please input student\'s name:') 41 phone = input('please input phone:') 42 studentinfo[name] = phone 43 write_file(studentinfo) 44 45 def modifiy_student(): 46 global studentinfo 47 name = input('please input student\'s name:') 48 if name in studentinfo: 49 phone = input('please input student\'s phone:') 50 studentinfo[name] = phone 51 else: 52 print('has no this name') 53 54 def show_all(): 55 global studentinfo 56 for key, value in studentinfo.items(): 57 print('name:' + key + 'phone:' + value) 58 59 func = {1 : search_student, \ 60 2 : delete_student, \ 61 3 : add_student, \ 62 4 : modifiy_student, \ 63 5 : show_all} 64 65 def menu(): 66 print('-----------------------------------------------'); 67 print('1 search student:') 68 print('2 delete student:') 69 print('3 add student:') 70 print('4 modifiy student:') 71 print('5 show all student') 72 print('6 exit') 73 print('-----------------------------------------------'); 74 75 def init_data(): 76 global studentinfo 77 file = open('student_info.txt', 'rb') 78 studentinfo = pickle.load(file) 79 #print(studentinfo) 80 file.close() 81 82 init_data() 83 while True: 84 menu() 85 index = int(input()) 86 if index == FUNC_NUM + 1: 87 exit() 88 elif index < 1 or index > FUNC_NUM + 1: 89 print('num is between 1-%d' % (FUNC_NUM + 1)) 90 continue 91 #print(index) 92 func[index]()
如有错误,或者更好的想法,请指教。