我已經對我的代碼進行了更改,以便程式運行包含程式的用戶名和密碼的整個檔案,但我得到反饋,只有用戶名“admin”可以訪問程式,而其他用戶不能訪問。
是否有另一種方法可以讓程式運行整個檔案并查看輸入的用戶名是否與檔案中的用戶名相同?
我的代碼如下:
定義登錄():
username = input("Enter your username: ")
password = input("Enter your password: ")
for line in open('user.txt', 'r').readlines():
field = line.strip().split(", ")
if username == field[0] and password == field[1]:
print('Welcome' username)
return True, field[0] == "admin"
return False, False
login_success, is_admin = login()
if login_success 和 is_admin: display_admin_menu_options() elif login_success: display_menu_options() else: print("用戶名或密碼不正確!")
uj5u.com熱心網友回復:
您的外部 return 陳述句位于 for 回圈內。嘗試:
def login():
username = input("Enter your username: ")
password = input("Enter your password: ")
for line in open('user.txt', 'r').readlines():
field = line.strip().split(", ")
if username == field[0] and password == field[1]:
print('Welcome' username)
return True, field[0] == "admin"
return False, False
我的猜測是admin在檔案的頂部user.txt。因此,只要您輸入管理員密碼和用戶名,它就會匹配欄位并回傳True,True. 但是,如果您輸入其他內容,它會跳過 if 陳述句并回傳False,False。您永遠不會回圈多次,因為您的 return 陳述句總是在第一個回圈中終止程式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/460633.html
