flag跳出多层循环
# 有时候我们需要从第三层的for循环直接跳出第二层的while循环,进入第一层循环,只用break就做不到了,这时候我们可以用flag. # (1)用法1: 定义标识为Ture,然后while flag,比如验证登录信息,验证成功直接改变标识状态为False,直接跳到第一层while循环(不执行else里的代码)/如果验证完都没成功,那么久执行else里面的代码 n = 1 while 1: # 阻塞等待客户端连接 conn, addr = server.accept() print('第%d个客户端连接成功' % n) flag = True count = 1 while flag: try: # 阻塞,等待接收 data = conn.recv(1024) data = data.decode('utf-8') a, b = data.split('_') print(a, b) # 打开文件进行验证 with open(r'D:\pythonproject\day28\02上次作业\2.用户登录作业\user_info', 'r') as f: for line in f: c, d = line.strip().split("_") print(c, d) if a == c and b == d: conn.send('success'.encode('utf-8')) flag = False break else: if count < 3: conn.send('fail'.encode('utf-8')) elif count == 3: conn.send('fail'.encode('utf-8')) break count += 1 except ConnectionResetError: break # (2)用法2: 在第二层while循环中,在执行某个操作之前定义标识(flag)状态,比如验证成功,就改变标识状态为Ture/验证完都不成过程,那么标识状态不变,之后根据标识状态再做操作. while 1: conn,addr=sock.accept() while 1: try: data=conn.recv(1024).decode("utf8") print("接收信息:",data) print("接收信息:",type(data)) print("-----",data.split("|")) user,pwd=data.strip().split("|") # 文件操作 flag=False with open("account","r") as f: for line in f: print("===",line.strip().split(":")) username,password=line.strip().split(":") if username==user and password==pwd: flag=True break if flag: conn.send(b"success") break else: conn.send(b"fail") except Exception as e: print(e) break