Python Code to Check the Strength of Password

In this blog, I am sharing a Python code that you can use to check the strength of a user’s password. I refer to it as a password checker in Python. This code evaluates the strength of a password based on the following criteria:

  • Length: At least 15 characters long.
  • Uppercase Letters: Includes at least one uppercase letter (e.g., A, B, C).
  • Lowercase Letters: Includes at least one lowercase letter (e.g., a, b, c).
  • Numbers: Contains at least one numeric digit (e.g., 0-9).
  • Special Characters: Includes at least one special character (e.g., @, #, $, %).

Based on the criteria met, the password is categorized as: Very Weak, Weak, Moderate, Strong, or Very Strong.

Here is the Python script to check password strength:

import re

def password_strength(password):
    """
    This function checks if the give password has at least 15 characters, upper and lower case characters, digits, and
    special characters. Using these criteria, it returns the strength of the password provided by the user.
    """
    length = len(password) >= 15
    has_upper = bool(re.search(r'[A-Z]', password))
    has_lower = bool(re.search(r'[a-z]', password))
    has_digit = bool(re.search(r'\d', password))
    has_special = bool(re.search(r'[!@#$%^&*(),.?":{}|<>]', password))

    score = sum([length, has_upper, has_lower, has_digit, has_special])
    return f"Password Strength: {['Very Weak', 'Weak', 'Moderate', 'Strong', 'Very Strong'][score-1]}"

def main():
    """
    password strength checker in Python
    """
    password = input("Enter a password: ")
    print(password_strength(password))

if __name__ == "__main__":
    main()

To run this code, save the script as pass_checker.py (or any name of your choice) and execute it using the following command:

python pass_checker.py

Please let me know in the comments if you find any errors in the code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.