【问题标题】:Python: Stopping a while loop from endingPython:停止一个while循环结束
【发布时间】:2017-06-23 15:33:58
【问题描述】:

基本上,我正在开发一个程序,它将登录详细信息存储到字典中,如果您的输入与附加的登录详细信息匹配,则允许您登录并调用 logging() 函数。但是,我的第二个菜单似乎有问题,它是 logs() 函数,它似乎不处理任何输入,而让它继续运行的 while 循环刚刚中断,它跳回询问您的登录详细信息再次(登录详细信息仍然有效)。当在logged() 菜单上输入空输入时,它应该说“那不是一个有效的选项,请再试一次。”,并且任何预期的输入都应该调用该函数,但他们仍然跳回再次询问登录详细信息。这些 while 循环目前对我来说有点太混乱了,我尝试将 validintro 变量切换为 True 或 False。帮助将不胜感激。

vault = {}

def menu(): 
    mode = input("""Hello {}, below are the modes that you can choose from:\n
    ##########################################################################
    a) Login with username and password
    b) Register as a new user
    To select a mode, enter the corresponding letter of the mode below
    ##########################################################################\n
    > """.format(name)).strip()
    return mode

def login():
    if len(vault) > 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 vault[username] == password:
                    print("Username matches!")
                    print("Password matches!")
                    logged() #jumps to logged function and tells the user they are logged on
            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.
        vault[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"]:
                return
            else:
                validinput = False
                register()
        return register

#LOGGED ONTO THE PASSWORD AND WEBSITE APP ADDING CONSOLE----------------------------------------------------------------------------------

def logged():
    print("You are logged in!\n")
    modea = input("""Below are the options you can choose:
    ##########################################################################\n
    1) Call test1 function
    2) Call test2 function
    3) Exit
    ##########################################################################\n
    > """).strip()
    return modea    

#Main routine
print("Welcome to the password vault program")
print("In this program you will be able to store your usernames and passwords in password vaults and view them later on.\n")
validintro = False
while not validintro:
    name = input("Hello user, what is your name?: ")
    if len(name) < 1:
        print("Please enter a name: ")
    elif len(name) > 30:
        print("Please enter a name no more than 30 characters: ")
    else:
        validintro = True
        print("Welcome to the password vault program {}.".format(name))

#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 = False

        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

validintro = False 
while not validintro:        
    option = logged()
    print(option) 
    if option == "1":
        test1()

    elif option == "2":
        test2()

    elif option == "3":
        break
    else:
        print("That was not a valid option, please try again: ")
        validintro = False 

print("Goodbye")

【问题讨论】:

    标签: python-3.x function while-loop return break


    【解决方案1】:

    logged() 函数中的循环的问题在于它丢失了!记录的功能只是打印菜单并读取输入。它不做任何其他事情。您需要添加类似的内容。

    def logged():
        print("You are logged in!\n")
        keeplooping = True
        while keeplooping:
            modea = input("""Below are the options you can choose:
            ##########################################################################
            1) Call test1 function
            2) Call test2 function
            3) Exit
            ##########################################################################
            > """).strip()
    
            if modea == "1":
                print("Run Test 1\n")
            elif modea == "2":
                print("Run Test 2\n")
            elif modea == "3":
                keeplooping = False
            else:
                print("That was not a valid option, please try again\n")
        return modea    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-13
      • 2019-03-15
      • 1970-01-01
      • 2022-01-22
      • 2022-10-31
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      相关资源
      最近更新 更多