qq33zz 发表于 2018-7-1 18:11:05

【python学习笔记】第034讲,丰富的else和with语句

动动手0

def file_compare(file1, file2):
    count = 0 # 统计行数
    differ = [] # 统计不一样的数量
    with open(file1) as f1,open(file2) as f2:
      for line1 in f1:
            line2 = f2.readline()
            count += 1
            if line1 != line2:
                differ.append(count)
      if len(differ) == 0:
            print('两个文件完全一样!')
      else:
            print('两个文件共有【%d】处不同:' % len(differ))
            for each in differ:
                print('第 %d 行不一样' % each)
      return differ

file1 = 'compare1.txt'
file2 = 'compare2.txt'
differ = file_compare(file1, file2)

动动手1
print('---------欢迎使用通讯录系统---------')
print('---------1、查询联系人资料---------')
print('---------2、添加一个新的联系人---------')
print('---------3、删除已有联系人---------')
print('---------4、退出通讯录系统---------')


def operation():
    a = input('请输入功能代码:')
    if a.isdigit() and int(a)<4:
      return int(a)
    else:
      return print('输入错误请从新输入')

d = {'MJ':11111}
while True:
    call=operation()
    if call == 1:
      name = input('请输入要查询的联系人姓名或者电话:')
      try:
            print (d)
      except:
            operation2 = input('该联系人不存在,是否添加该联系人?(Y/N)')
            while True:
                if operation2 in ('y','Y'):
                  call = 2
                  break
                elif operation2 in ('n','N'):
                  break
    ifcall == 2:
      while True:
            print('请依次输入资料')
            name = input('==>姓名:')
            try:
                d
                print('联系人已存在!')
                print(name+':%d'%d)
                continue
            except:
                tel=input('==>电话:')
                age=input('==>年龄:')
                job=input('==>职位:')
                d=['名字:'+name,'电话:'+tel,'年龄:'+age,'职位:'+job]
                print('添加成功!')
                break
    if call == 3:
      name=input('请输入需要删除的联系人名字:')
      try:
            del d
            print('已经删除联系人%s'%name)
      except:
            print('不存在的联系人!')
    if call == 4 :
      print('-----感谢使用联系人系统,再见!-----')
      exit()
    continue
不是很懂通讯录的修改用处是什么,感觉之前的if——else就挺好,现在改了可读性感觉没那么高了,请高手指点一二。顺便问下if--else和try--except的分别用在什么地方会比较好
页: [1]
查看完整版本: 【python学习笔记】第034讲,丰富的else和with语句