列表索引错误超出范围

2024-04-25 22:15:40 发布

您现在位置:Python中文网/ 问答频道 /正文

当我运行我的代码时,我得到这样一条消息:如果username==Login\u info[0]和password==Login\u info[1]:indexer:list index out of range“
我的代码以前可以工作,但我不明白为什么它不再工作了。你知道吗

#Registration
def Register():
    username = input("Please input the first 3 or 4 letters of your first name and your year: ")#Gets the user to create a username
    validate()#Calls upon the password validate()
    file = open("AccountFile.txt","a") #Opens the text file called "AccountFile"
    file.write(username)#Writes the users username into the text file.
    file.write(" ")
    file.write(password)#Writes the users password into the text file.
    file.write("\n")
    file.close()#Closes the text file "AccountFile"
#Login
def Login():
    username = input("Please enter your username: ") #Asks the user to enter their username that they created
    username = username.strip() #Any spaces that the user may put in will not affect the code and be removed
    password = input("Please enter your password: ") #Ask the user to enter their password that they created
    password = password.strip() 
    for line in open("AccountFile.txt","r").readlines(): #Reads the lines in the text file "AccountFile"
        login_info = line.split() #Split on the space, and store the results in a list of two strings
        if username == login_info[0] and password == login_info[1]:
            print("You have succesfuly logged in!") #Lets the  user know that they have succesfully logged in
            return True
    print("Incorrect credentials.")
    return False
#Validation
def validate():
    while True:
        global password #Makes the password global meaning the function global can be called upon anywhere in the code
        password = input("Enter a password: ") #Asks the user to create a password
        password = password.strip()         
        if len(password) < 8: #Checks whether the password is at least 8 letters long
            print("Make sure your password is at least 8 letters")
        elif re.search('[0-9]',password) is None: #Makes sure that the password has a number in it
            print("Make sure your password has a number in it")
        elif re.search('[A-Z]',password) is None: #Makes sure the password has a capital letter in it
            print("Make sure your password has a capital letter in it")
        else:
            print("Your password seems fine")
            break
#DisplayMenu
def DisplayMenu():
    status = input("Are you a registered user? y/n? ") #Asks the user if they already have a registered account
    status = status.strip() 
    if status == "y":
        Login()
    elif status == "n":
        Register()
DisplayMenu()

Tags: thetextininfoinputyourthatusername