Home > front end >  Python login program using textfiles
Python login program using textfiles

Time:06-30

Im new to python and I'm trying to code a python login program. Instead of printing out "Welcome to the database" when the username provided is correct, it printed out both "Welcome to the database" and "Username invalid. Please try again.". May I know which part of my code needs to be corrected?

def login():
    while True:
        name = input("Name: ")
        with open('username.txt', "r")as name_file:
            for line in name_file.readlines():
                if name == line.strip():
                    print("welcome to database")
                else:
                    print("Username invalid. Please try again")

CodePudding user response:

You are looping through all the users in the text file and for each of them printing to the console. The thing you probably want could be done like this:

def login():
    while True:
        loginSucessful = False
        name = input("Name: ")
        with open('username.txt', "r")as name_file:
            for line in name_file.readlines():
                if name == line.strip():
                     loginSucessful = True
                     break
            if loginSucessful:            
                print("welcome to database")
            else:
                print("Username invalid. Please try again")

CodePudding user response:

You could use a boolean variable to keep track of successful logins like @Michalor did. Or you can use Python's for/else loop to do the same thing without adding a new variable. If the login is successful and you break out of the loop, the "else" statement isn't executed. Using "break" also has the advantage that you don't need to test all of the other users after you have found a successful login.

def login():
    while True:
        name = input("Name: ")
        with open('username.txt', "r")as name_file:
            for line in name_file.readlines():
                if name == line.strip():
                    print("welcome to database")
                    break
            else:
                print("Username invalid. Please try again")

Of course, this kind of function doesn't provide much security, as you can keep guessing the names in the text file until you find a valid one, or if you can get your hands on the text file itself you can just look the names up. For actual login code, it's probably best to use some kind of login library that handles the security details for you.

  • Related