[py]for else案例

来源:互联网 发布:网络延迟检测 编辑:程序博客网 时间:2024/09/21 09:20

实现了删除用户时候

  • 1,如果这个人不存在,则提示用户不存在
  • 2,如果存在,删除后,提示用户删除成功
def txl_del():  flag = 0  name = raw_input("delete name > ")  for info in txl:    if info['name']==name:        txl.remove(info)        flag=1        break  else:    print "cha wu ci ren"  if flag:    print "del user sucessful"  txl_save()

第二个需求这样写更简单一些

def txl_del():    '''删除用户    实现了删除用户时候,    1,如果这个人不存在,则提示用户不存在    2,如果存在,删除后,提示用户删除成功    '''    flag = 0    name = raw_input("delete name > ")    for info in txl:        if info['name']==name:            txl.remove(info)            flag=1            print "del user sucessful"            break    else:        print "cha wu ci ren"    txl_save()

另一个栗子

需求: 查询用户,当用户不存在时候,提示查无此人

def txl_search():    '''查询用户信息'''    name = raw_input("the people you want to search> ")    for line in txl:        if line['name']==name:            print "name\t\tage\t\tgender\t\ttel"            print "---------------------"            print ("%(name)s\t\t%(age)s\t\t%(gender)s\t\t%(tel)s") % line            break    else:        print "cha wu ci ren"
原创粉丝点击