简体   繁体   中英

Why does my program keep throwing an index out of range error?

I programme in C# and have programmed in python previously but that was years ago and to a very basic level. Someone I know has created the following code to but it keeps throwing an list index out of range error and I do not know why. The code is supposed to ask the user for a username and password, loop through every line in a file and check if the username and password match the username and password from any lines. The files stores a username and password pair on one line with a space in between them. Different username and password pairs are placed on separate lines.

The code throws the error when an incorrect password and/or username is inputted which is not in the file.

The code is as follows:

       file = open("user_details.txt","r")
       lines = file.readlines()
       file.close()
       while True:
          username = input("Please enter your username ")
          password = input("Please enter your password ")
          for line in lines: 
              login_info = line.split()
              if username == login_info[0] and password == login_info[1]:
                  print("Correct credentials!")
                  return True
          print("Incorrect credentials.")

The file had empty lines in it. The program was currently being tested and the person who wrote the code accidentally pressed enter and created a blank line in the file. By removing this, the code worked. This is because the line.split() was unsuccessful for blank lines so accessing the first and last elements from the list gave an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM