注冊和登錄功能單用戶版
注冊
count = 0
while count < 3:
username_inp = input('請輸入你的用戶名:')
pwd_inp = input('請輸入你的密碼:')
re_pwd_inp = input('請再次輸入密碼:')
if not pwd_inp == re_pwd_inp:
print('兩次輸入的密碼不一致')
count += 1
continue
with open('user_info.txt','w',encoding='utf8') as fa:
fa.write(f'{username_inp}:{pwd_inp}\n')
fa.flush()
break
登錄
username_inp = input('請輸入你的用戶名:')
pwd_inp = input('請輸入你的密碼:')
with open('user_info.txt','r',encoding='utf8') as fr:
for user_info in fr:
username,pwd = user_info.split(':')
if username.strip() == username_inp and pwd.strip() == pwd_inp:
print('登錄成功')
break
else:
continue
else:
print('用戶名或密碼錯誤')
注冊和登錄功能優化版
打開用戶名和密碼信息庫
import time
with open('user_info.txt', 'r', encoding='utf8') as fr: # 打開信息表
ls = fr.read().split('|') # 取出信息放入列表
ls1 = ls[0:-1]
dic_username = {}
for user_info in ls1: # 把信息列表轉換成字典
ls2 = user_info.split(':')
dic_username[ls2[0]] = ls2[1]
注冊
count = 0
while count < 3:
user_name = input('請輸入用戶名:')
if user_name in dic_username: # 判斷用戶名是否重名
print('該用戶名已被注冊,請用其他用戶名')
if count == 2: # 限制次數,防止惡意攻擊
print('超過三次,等一分鍾后再試')
time.sleep(5) # 休眠5秒鍾
count = 0 # 再次啟動當前while循環
else:
pwd_inp = input('請輸入密碼:')
re_pwd_inp = input('請再次輸入密碼:')
if not pwd_inp == re_pwd_inp:
print('兩次輸入的密碼不一致')
if count == 2: # 限制次數,防止惡意攻擊
print('超過三次,等一分鍾后再試')
time.sleep(5) # 休眠5秒鍾
count = 0 # 再次啟動當前while循環
else:
with open('user_info.txt','a',encoding='utf8') as fa:
fa.write(f'{user_name}:{pwd_inp}|')
print('注冊成功')
fa.flush()
break
count += 1 # 注意這一步的縮進層級
登錄
count_login = 0
while count_login < 3:
username_inp = input('請輸入你的用戶名:')
pwd_inp = input('請輸入你的密碼:')
key_name = username_inp.strip()
value_pwd = pwd_inp.strip()
if key_name in dic_username and dic_username[key_name] == value_pwd:
print('登錄成功')
else:
print('用戶名或密碼錯誤')
if count_login == 2: # 限制次數,防止惡意攻擊
print('超過三次,請一分鍾后再試')
time.sleep(5) # 休眠5秒鍾
count_login = 0 # 再次啟動當前while循環
count_login += 1