Home > OS >  my login code prints for each line in the text file im using instead of just printing one output for
my login code prints for each line in the text file im using instead of just printing one output for

Time:11-16

my code:

userlog = input("What is your username?")
passlog = input("What is your password?")
for fileread in open("accounts.txt", "r").readlines():
    file = fileread.split()
    if userlog == file[0] and passlog == file[1]:
        print("Succesfully logged in")
    elif userlog != file[0] and passlog != file[1]:
        print("Username or password is incorrect")

instead of printing just "Succesfully logged in" or "Username or password is incorrect" it prints "Username or password is incorrect" for all lines in the text file and when the login info is typed correct it does the same but one is replaced with "Succesfully logged in"

I don't have a single clue what to do I'm obviously pretty new to python.

CodePudding user response:

You can try following solution:

    userlog = input("What is your username? ")
    passlog = input("What is your password? ")
    for fileread in open("accounts.txt", "r").readlines():
        file = fileread.split()
        if userlog == file[0] and passlog == file[1]:
            print("Successfully logged in")
            break
    else:
        print("Username or password is incorrect")

You should break a for loop if a user successfully logs in.

If whole loop completes without break else code will be executed.

Have a look at this link: https://book.pythontips.com/en/latest/for_-_else.html#else-clause

CodePudding user response:

One addition you can have is to break the loop when the login is successful:

userlog = input("What is your username?")
passlog = input("What is your password?")
for fileread in open("accounts.txt", "r").readlines():
    file = fileread.split()
    if userlog == file[0] and passlog == file[1]:
        print("Succesfully logged in")
        break
  • Related