【发布时间】:2013-05-23 22:22:55
【问题描述】:
我是 Python 新手,我在下面编写了这段代码。这只是一个简单的登录代码,允许您注册或登录。
现在我可以登录了。如您所见,我将用户名和密码放在变量 database 中。
在register() 函数中,我试图以(用户名、密码)的形式将newusername 和newpassword 添加到database 列表中,以便login() 函数看到它。
import time
import sys
import getpass
database = [
("Test1", "123"),
("Test2", "000")
]
def login():
time.sleep(1)
print("Welcome. Please login.")
while True:
time.sleep(1)
username = input("Username: ")
password = getpass.getpass("Password: ")
time.sleep(1)
if (username, password) in database:
print("Welcome, " + username)
main()
else:
print("User not found. Try again.")
def logout():
time.sleep(1)
print("Logout?")
lgout = input(">>")
if lgout == ("yes") or lgout == ("Yes") or lgout == ("YES"):
time.sleep(1)
print("Logout successful")
main2()
elif lgout == ("no") or lgout == ("No") or lgout == ("NO"):
print("Logout unsuccessful")
main()
else:
print("Command not valid")
def main():
time.sleep(1)
print("Current commands: Logout")
while True:
command = input(">>")
if command == ("Logout"):
logout()
else:
print("Command not valid")
def main2():
time.sleep(1)
print("Hello, would you like to login, register or exit?")
while True:
command2 = input(">>")
if command2 == ("Login") or command2 == ("login") or command2 == ("LOGIN"):
login()
elif command2 == ("Register") or command2 == ("register") or command2 == ("REGISTER"):
register()
elif command2 == ("Exit") or command2 == ("exit") or command2 == ("EXIT"):
sys.exit()
else:
print("Command not valid")
def register():
print("Register your information below")
newusername = input("Username: ")
newpassword = getpass.getpass("Password: ")
print("Success! Please login!")
login()
main2()
遗憾的是,database["newusername"] = newpassword 不起作用,因为它不是字典。
【问题讨论】:
-
您可能需要考虑实际使用字典,因为元组很快就会变得非常疯狂。
database = {'user1': {'password':'abc123'}, 'user2': {'password':'xyz321'}}是我建议的数据库格式。这样,如果您想检查密码,您只需转到if password == database['username']['password']: main(),如果您想添加新用户,您只需将您的 register() 设置为database[newusername] = {'password':newpassword} -
嘿,使用会话来改进登录。其次使用 django 或其他一些框架。你很快就会习惯它们。
-
我按照 TehTris 所说的进行操作,现在好多了,因为我注意到元组不能从中删除元素,因此当我尝试添加删除用户功能时,它会变得更加困难。非常感谢