gpt4 book ai didi

python-3.x - Python 3 使用字典的登录程序

转载 作者:行者123 更新时间:2023-12-02 17:28:51 24 4
gpt4 key购买 nike

我正在尝试为一个项目创建一个登录程序,但我似乎无法弄清楚两件事。第一个是退出程序后如何将登录信息存储在字典中,第二个是弄清楚如何正确退出程序。谢谢!这是源代码。

#Dictionary
users = {}
#Used to quit/create/login users
status = ""
#Start Menu:Ask if user exists or create new user
def Display_Menu():
status =input("Are you a registered user? (Yes/No)? Press q to quit: ")
if status == "Yes":
Old_User()
elif status == "No":
New_User()
#Creates New User
def New_User():
Create_Login =input("Create login name: ")
if Create_Login in users:
print ("Login name already exist!")
else:
Create_Password =input("Create password: ")
users[Create_Login] = Create_Password
print("New User created!")
#Login if old user
def Old_User():
login =input("Enter login name: ")
Password =input("Enter password: ")

if login in users and users[login] == Password:
print("Login successful!")
else:
print("User doesn't exist or wrong password!")
#Quits Program
if status == "q":
exit()
while status !="q":
Display_Menu()

最佳答案

嗯,Python程序不会将数据存储在内存中,所以我想说,你应该创建一个login_data.txt

代码可能看起来像这样

import json # may not be required as per storing method

#Dictionary
with open("login_data.txt", "r") as login_file:
try:
users = json.load(login_file)
except:
users = {}
#Used to quit/create/login users
status = ""
#Start Menu:Ask if user exists or create new user
def Display_Menu():
status =input("Are you a registered user? (Yes/No)? Press q to quit: ")
if status == "Yes":
Old_User()
elif status == "No":
New_User()
#Creates New User
def New_User():
Create_Login =input("Create login name: ")
if Create_Login in users:
print ("Login name already exist!")
else:
Create_Password =input("Create password: ")
users[Create_Login] = Create_Password
print("New User created!")
#Login if old user
def Old_User():
login =input("Enter login name: ")
Password =input("Enter password: ")

if login in users and users[login] == Password:
print("Login successful!")
else:
print("User doesn't exist or wrong password!")
#Quits Program (modified)
while True:
if status in {"q", "Q"}:
# store the data before quitting
with open("login_data.txt", "w") as login_file:
json.dump(users, login_file)
break
else:
Display_Menu()

至于退出,Python程序执行完所有代码后自动退出。因此,在遇到 break 语句后,程序会脱离 while 循环,并且由于之后没有更多代码,程序会自动退出。

关于python-3.x - Python 3 使用字典的登录程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20061307/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com