簡體   English   中英

如何在Python的數據庫列表中添加新的用戶名和密碼?

[英]How do I add a new username and password to a database list in Python?

我是Python的新手,我在下面做了此代碼。 這只是一個簡單的登錄代碼,使您可以注冊或登錄。

現在,我可以登錄了。 如您所見,我將用戶名和密碼放在變量database

在函數register()我嘗試將newusernamenewpassword以(用戶名,密碼)的形式添加到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無效,因為它不是字典。

您在此處的“數據庫”是元組列表。

要將某些內容附加到列表的末尾,請使用.append()。 要構造元組,請使用包含用逗號分隔的值的括號。 將這兩個放在一起:

database.append( (newusername, newpassword) )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM