【问题标题】:Python: Calling function through while loopPython:通过while循环调用函数
【发布时间】:2017-06-22 23:18:25
【问题描述】:

我正在尝试将我的程序扩展为将登录详细信息存储在字典中的程序,当您尝试登录时,它应该询问您的用户名和密码,以及登录详细信息是否与附加的匹配到字典中,它会说“您已登录!”,但我似乎根本无法调用我的 login() 函数,除了当我没有输入登录详细信息但它不会循环返回时打印出 else 打印语句到 menu() 就像它应该的那样,因为我把它放在一个 while 循环中。我想我在主程序中搞砸了我的while循环,但似乎无法理解它。帮助将不胜感激。

store = {}

def menu(): 
    mode = input("""Hello, below are the modes that you can choose from:\n
    ##########################################################################
    a) Login with login details
    b) Register login details
    To select a mode, enter the corresponding letter of the mode below
    ##########################################################################\n
    > """).strip()
    return mode

def login():
    if len(store) > 0 : #user has to append usernames and passwords before it asks for login details
        print("Welcome to the login console")
        while True:
            username = input ("Enter Username: ") 
            if username == "":
                print("User Name Not entered, try again!")
                continue
            password = input ("Enter Password: ") 
            if password == "":
                print("Password Not entered, try again!")
                continue
            try:
                if store[username] == password:
                    print("Username matches!")
                    print("Password matches!")
                    logged() #jumps to logged function and tells the user they are logged on
                    break 
            except KeyError: #the except keyerror recognises the existence of the username and password in the list
                print("The entered username or password is not found!")

    else:
        print("You have no usernames and passwords stored!")

def register(): #example where the username is appended. Same applies for the password
    print("Please create a username and password into the password vault.\n")

    while True:
        validname = True
        while validname:
            username = input("Please enter a username you would like to add to the password vault. NOTE: Your username must be at least 3 characters long: ").strip().lower()
            if not username.isalnum():
                print("Your username cannot be null, contain spaces or contain symbols \n")
            elif len(username) < 3:
                print("Your username must be at least 3 characters long \n")
            elif len(username) > 30:
                print("Your username cannot be over 30 characters \n")
            else:
                validname = False 
        validpass = True

        while validpass:
            password = input("Please enter a password you would like to add to the password vault. NOTE: Your password must be at least 8 characters long: ").strip().lower()
            if not password.isalnum():
                print("Your password cannot be null, contain spaces or contain symbols \n")
            elif len(password) < 8:
                print("Your password must be at least 8 characters long \n")
            elif len(password) > 20:
                print("Your password cannot be over 20 characters long \n")
            else:
                validpass = False #The validpass has to be True to stay in the function, otherwise if it is false, it will execute another action, in this case the password is appended.
        store[username] = password
        validinput = True
        while validinput:
            exit = input("\nEnter 'end' to exit or any key to continue to add more username and passwords:\n> ")
            if exit in ["end", "End", "END"]:
                menu()
                break
            else:
                validinput = False
                register()
        return register

def logged():
    print("----------------------------------------------------------------------\n")
    print("You are logged in!")


#Main routine

#The main program to run in a while loop for the program to keep on going back to the menu part of the program for more input till the user wants the program to stop
validintro = False 
while not validintro: 
        chosen_option = menu() #a custom variable is created that puts the menu function into the while loop
        validintro = True

        if chosen_option in ["a", "A"]:
            login()

        elif chosen_option in ["b", "B"]:
            register()

        else:
            print("""That was not a valid option, please try again:\n """)
            validintro = False

【问题讨论】:

    标签: python-3.x function loops dictionary while-loop


    【解决方案1】:

    这是因为在打印“您没有存储用户名和密码!”之后,您返回到外部 while 但从未将 validintro 更改为 false。这会导致您的 while 循环结束。

    您应该从 login 返回一个值以了解是否没有用户并在 while 中检查该值,或者在 login 函数中,在 else 部分将全局 validintro 设置为 false(我会推荐第一种方式。 )

    【讨论】:

    • 确实如此。我认为如果你把最后一行提高一级(与 if 和 elsif 相同),你应该没问题。但我认为你应该省略整个validintro的事情。只需使用 While True,添加菜单项 q 以退出并在用户选择 q 时添加中断。
    猜你喜欢
    • 2020-06-16
    • 2017-11-24
    • 1970-01-01
    • 2016-07-23
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 2015-07-26
    相关资源
    最近更新 更多