In this Python tutorial, learn how to validate a username and password by using equality (==), if/else statement and while not complete loop in Python. In addition, the usernames and passwords will be stored in a Python dictionary for validation. I am running Python IDLE (Python GUI) version 3.7.
Python Dictionary
A Python dictionary is also known as an associative array and is a Python data structure. The Python dictionary consists of key-value pairs and each key-value pair is mapped to an associated value of the key.
The dictionary is enclosed by comma separation between the key-value pairs and a colon separates the key and value in the pair. As shown below, the key is the username and the value is the password associated with the key.
1 2 3 | user = {"username1" : "12345", "username2" : "67890" } |
Python while Loop and if/elif Statement
The Python while loop will continuously loop until the loop matches False. For example, the below username and password validation while loop is set to not complete. The complete variable is set to False and the while loop is continuously running until it meets the complete = True in the if statement. When the while loop meets the equality validation of the if statement, the while loop will no longer execute when the complete variable is set to True and in return, the while loop will equal true.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | complete = False user = {"username1" : "12345", "username2" : "67890" } while not complete: username = input("Username: ") password = input("Password: ") if username == user and password == password: continue elif username not in user: print("This is not a valid username, input username again!") continue elif password != user[username]: print(f"Password is not valid for {username}. ") continue elif password == user[username]: print(f"Welcome {username} ") print(f"Thank you for logging on. ") complete = True print ("Username and Password Validated in Python") |
This is a very basic way to validate a username and password in Python, and should only be used as a reference to understand the basics of validating a username and password. One should ALWAYS use a hash when using passwords.