我现在的问题是我的字典使用键:值到储存用户名:密码为每次我重新运行程序键:值为重置,字典将再次设置为空。我的程序的目标是让一个人用用户名和密码登录,并能够存储注释和密码(我是用python.txt文件完成的)。然后下一个人可以来,创建一个帐户,并做同样的事情。以下是我的代码(我对与我的问题相关的每一行代码都进行了注释):
def userPass():
checkAccount = input("Do you have an account (Y or N)?")
if (checkAccount == 'N' or checkAccount == 'n'):
userName = input("Please Set Your New Username: ")
password = input("Please Set Your New Password: ")
// if (userName in dictAcc):
print("Username is taken")
userPass()
else:
// dictAcc[userName] = password
print("Congratulations! You have succesfully created an account!")
time.sleep(1.5)
dataInput()
elif(checkAccount == 'Y' or checkAccount == 'y'):
login()
else:
print("Invalid answer, try again")
userPass()
def login():
global userName
global password
global tries
loginUserName = input("Type in your Username: ")
loginPass = input("Type in your Password: ")
if (tries < 3):
// for key in dictAcc:
// if (loginUserName == key and loginPass == dictAcc[key]):
// print("You have successfully logged in!")
dataInput()
else:
print("Please try again")
tries += 1
login()
if (tries >= 3):
print("You have attempted to login too many times. Try again later.")
time.sleep(300)
login()
userPass()
有不同的方法可以做到这一点。我要提两个。在
正如您所注意到的,当程序完成执行时,程序创建的所有变量都将被删除。在
使这些变量保持活动状态的一种方法是使程序不确定地运行;类似于后台进程。这可以非常简单地通过在while循环
while True:
中运行脚本来实现,尽管还有更有效的方法来实现。然后,它的变量可以继续存在,因为程序永远不会终止。在但是,这只在您希望某个东西一直运行的情况下才有用,例如等待输入的用户界面。大多数时候,您希望脚本运行并能够完成。在
因此,您可以将所需的数据输出到文本文件中。然后,当你启动你的程序,阅读文本文件并将信息组织到你的字典中。这将使用
open("Your_username_file")
并读取该文件的数据。如果您需要有关如何执行此操作的帮助,有许多关于how to read information from files in Python的教程。在正如其他人所提到的,您需要将字典保存到一个文件中,并在重新启动程序时加载它。我调整了您的代码以适合我,并创建了两个函数,一个用于保存字典(
savedict
),另一个用于加载字典(loaddict
)。except IOError
部分只是为了在不存在的情况下创建一个新文件。在请注意,一般来说,在文本文件中存储密码是一个非常糟糕的主意。如果您尝试打开
"dictAcc.txt"
文件(其中包含所有密码),您可以清楚地看到原因。在在您的情况下,如何存储它并不重要,因此最好保持简单并将其存储在文本文件之类的文件中。无论如何,你不想在内存中存储帐户,因为你需要让它永远运行。在
由于这也是在本地运行的,无论你选择如何存储密码,任何使用它的人都可以访问它。这样用户就可以检查用户的帐户和密码。在
所以在存储密码之前,您需要对密码进行加密。没有听起来那么难。实际上,Python有内置的库来处理它。在
快速的google搜索返回了一个简单的教程,解释了所有这些步骤,check it out。您可能能够很快地将其实现到您的代码中。在
相关问题 更多 >
编程相关推荐