w3resource

Python user authentication using Boolean logic


10. Authentication Checker

Write a Python program that checks a simple authentication system. The program verifies the provided username and password against predefined usernames and passwords by using boolean checks.

Sample Solution:

Code:

def user_authentication(username, password):
    # Predefined usernames and passwords
    predefined_users = {
        "empdb1": "Jue@3$juy0",
        "empdb2": "juRe34@$",
        "admin": "koiUaq$&@ki"
    }
    
    if username in predefined_users and predefined_users[username] == password:
        return True
    else:
        return False

def main():
    try:
        username = input("Input your userid: ")
        password = input("Input your password: ")
        
        if user_authentication(username, password):
            print("Authentication has been successful. Welcome!", username)
        else:
            print("Authentication failed. Invalid username or password.")
    except Exception as e:
        print("An error occurred:", e)

if __name__ == "__main__":
    main()

Output:

Input your userid: empdb2
Input your password: juRe34@$
Authentication has been successful. Welcome! empdb
Input your userid: admin
Input your password: kojUaq$&@ki
Authentication failed. Invalid username or password.

In the above exercise the program prompts the user to input a username and password. Using the "user_authentication()" function, it then checks if the provided credentials match the predefined credentials. Finally it prints the appropriate message based on the authentication results.

Flowchart:

Flowchart: Python user authentication using Boolean logic.

For more Practice: Solve these Related Problems:

  • Write a Python program to implement a simple authentication system that checks a username and password against predefined values using boolean expressions.
  • Write a Python function to validate user credentials from a dictionary and return True if the username and password match, else False.
  • Write a Python script to simulate an authentication process where boolean checks determine if access is granted based on input credentials.
  • Write a Python program to verify a login attempt by comparing input username and password with stored credentials using a series of boolean conditions.

Go to:


Previous:Python circle area check using Boolean logic.
Next: Python None Data Type Exercises Home.

Python Code Editor :

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.