Introduction:
Password security is a crucial aspect of online safety. A good password is one that is complex enough to be difficult for unauthorized users to guess or crack. In this program, we will validate whether a given password meets a set of predefined criteria, including length, the presence of uppercase letters, numbers, and special characters. This program is written in Python and provides an easy way to enforce strong password rules in any application or system.
Objective:
The objective of this program is to verify that a password meets the following criteria:
- At least 8 characters in length.
- Contains at least one uppercase letter.
- Contains at least one number.
- Contains at least one special character (such as @, #, $, etc.).
Now, let’s look at the Python code for the password validation program:
# Password validation program
import re
def validate_password(password):
# Check password length
if len(password) < 8:
return "Password must be at least 8 characters long."
# Check for uppercase letter
if not re.search(r'[A-Z]', password):
return "Password must contain at least one uppercase letter."
# Check for digit
if not re.search(r'[0-9]', password):
return "Password must contain at least one digit."
# Check for special character
if not re.search(r'[@$!%*?&]', password):
return "Password must contain at least one special character: @$!%*?&."
return "Password is valid!"
# Main program
if __name__ == "__main__":
# User input for password
user_password = input("Enter a password to validate: ")
result = validate_password(user_password)
print(result)
Explanation of the Program Structure:
- Importing Regular Expression (re) module: We use the
re
module to check if the password contains uppercase letters, digits, and special characters. There.search()
function searches the string for the specified pattern. - Password validation function: The function
validate_password
checks each of the criteria one by one, returning an appropriate message if the password does not meet the required conditions. If all conditions are met, it returns a success message indicating that the password is valid. - Main Program: In the main program, the user is prompted to enter a password. The program then calls the
validate_password
function with the entered password and prints the result of the validation.
How to Run the Program:
- Ensure you have Python installed on your computer. If not, download and install Python from here.
- Copy the provided code into a Python file, e.g.,
password_validation.py
. - Open a terminal or command prompt, navigate to the directory where the file is saved, and run the script using the command:
python password_validation.py
. - You will be prompted to enter a password. The program will validate whether it meets the criteria and display the result.
Copyright Information:
© 2024 Learn Programming. All rights reserved.