[英]Am I doing this wrong?
我剛剛開始學習 Python 編程,我正在嘗試制作一個登錄系統,它使用終端並將數據存儲到 JSON 文件中並檢索它以登錄。
這是看起來導致問題的部分。
def login():
login_username = input("Enter your username: ")
login_password = input("Enter your pass: ")
with open("data.json", 'r+') as data:
if login_username == username and login_password == password:
print("Successful Login")
else:
print("Please Try Again")
login()
當我被要求輸入用戶並通過並且輸入與來自 JSON 的數據匹配時,它將循環並一次又一次地要求輸入用戶名和密碼。
我的整個代碼如下
import json
uname = ""
password =""
def register():
uname = input("Enter a user to log in with: ")
password = input("Enter a password: ")
confirmed_pass = input("Enter the above password again")
if password != confirmed_pass:
print("Both the passwords does not match please re-enter a pass")
password = input("Enter a password:")
confirmed_pass = input("Enter the above password again")
login_info = {
"Username": uname,
"Password": password
}
with open("data.json", "w") as write_file:
json.dump(login_info, write_file, separators=(',', ':'))
log = input("Would you like to login? (Y/N)")
if log == 'Y' or log == "y":
login()
else:
quit()
def login():
login_uname = input("Enter your username: ")
login_password = input("Enter your pass: ")
with open("data.json", 'r') as data:
if login_uname == uname and login_password == password:
print("Successful Login")
else:
print("Please Try Again")
login()
reg = input("Have you registered (Y/N) ?: ")
if reg == 'Y' or reg == 'y':
login()
elif reg == 'N' or reg == 'n':
register()
else:
print("Error!")
根據您的代碼,您應該首先使用json.loads將數據加載到 python 字典中:
with open("data.json", 'r') as data:
login = json.loads(data.read())
# then you can use it like this
if login_username == login['Username'] and login_password == login['Password']:
... Rest of the code
只是您的登錄僅適用於最后注冊的用戶,您應該解決這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.