Python做的第一个小项目-模拟登陆
1. 用户输入帐号密码进行登陆
2. 用户信息保存在文件内
3. 用户密码输入错误三次后锁定用户
主要采用循环语句和条件语句进行程序流程的控制,加入文件的读写操作
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 while True: 2 choice = input("登陆L 注册R 退出Q:").strip() 3 #用户登录流程 4 if choice.lower() == 'l': 5 l_flag = False 6 count = 1 7 tmp = '' 8 while True: 9 user_name =input("请输入用户名(或者'q'退出):").strip() 10 if not user_name:continue 11 if user_name == 'q': 12 print("退出成功!") 13 exit() 14 user_pwd = input("请输入用户密码(或者'q'退出):").strip() 15 if not user_pwd: 16 print("密码不能为空,请重新输入!") 17 continue 18 if user_pwd == 'q': 19 print("退出成功!") 20 exit() 21 with open("locked_id",mode="r",encoding="utf8") as f_locked: 22 for line in f_locked: 23 if line.startswith("username:") and user_name in line and len(user_name)!=0: 24 print("该用户已经被锁定,请联系管理员!") 25 exit() 26 with open("user_id",mode="r",encoding="utf8") as f_reed: 27 for line in f_reed: 28 if line.startswith("username:") and user_name in line and len(user_name) != 0: 29 l_flag = True 30 tmp = line 31 if l_flag: 32 if tmp.split(":")[2].strip() == user_pwd: 33 print("用户登录成功!") 34 l_flag = False 35 exit() 36 elif count >= 3: 37 with open("locked_id",mode="a",encoding="utf8") as f_locked: 38 f_locked.write("\nusername:"+user_name) 39 print("您的密码错误三次,用户被锁定!") 40 l_flag =False 41 exit() 42 else: 43 count += 1 44 l_flag =False 45 print("密码错误,请重新输入!") 46 continue 47 else: 48 print('用户名不存在,请重新登录!') 49 50 #用户注册流程 51 if choice.lower() == 'r': 52 r_flag = False #注册过程标志位 53 while True: 54 new_user_name =input("请输入注册用户名(或者'q'退出):").strip() 55 if not new_user_name:continue #用户名为空开始下一个循环 56 if new_user_name == 'q': 57 print("退出成功!") 58 exit() 59 new_pwd = input("请输入用户密码且不少于6位(或者'q'退出):").strip() 60 if new_pwd == 'q': 61 print("退出成功!") 62 exit() 63 if len(new_pwd) < 6: 64 print('密码不能为空且不少于6位!') 65 continue 66 with open("user_id",mode="r+",encoding="utf8") as f: 67 f.seek(0) 68 for line in f: 69 if line.startswith("username:") and new_user_name in line: #判断是否已经有该用户 70 print("该用户已经被注册!") 71 r_flag = True 72 break 73 if not r_flag: 74 f.write("\nusername:" + new_user_name) 75 f.write("\t|password:" + new_pwd) 76 print("新用户注册成功!") 77 r_flag = False 78 break 79 80 #退出流程 81 if choice.lower() == 'q': 82 print("退出成功!") 83 exit()
人生苦短,我用Python