Password Strength Checker

UpComing SoftWare Training Demos

πŸš€ *Gen AI EngineerΒ Telugu (Production Focused)*
πŸ—“οΈ *Date:* 30th Sept 2026, 07:00AM IST
πŸ“ *Register Now!:*
https://www.vlrt.in/gr
πŸ‘₯ *Join WA Community:*
https://www.vlrt.in/gw
πŸ’‘*Course Content:*
https://www.vlrt.in/ai
▢️ *Demo Videos:*
https://www.vlrt.in/gv

πŸš€ *Service now Admin/ Development (ITSM)FREE Demo in Telugu*
πŸ—“οΈ *Date:* 30th Sept 2026, 08:00AM IST
πŸ“ *Register Now!:*
https://www.vlrt.in/7r
πŸ‘₯ *Join WA Community:*
https://www.vlrt.in/7w
πŸ’‘*Course Content:*
https://www.vlrt.in/7c
▢️ *Demo Videos:*
https://www.vlrt.in/7v

πŸš€ *Vulnerability Management Training Demo*
πŸ—“οΈ *Date:* 30th Sept 2026, 09:00 AM IST
πŸ“*Register Now!:*
https://www.vlrt.in/vr
πŸ‘₯ *Join Community:*
https://www.vlrt.in/cw
πŸ’‘ *Course Content:*
https://www.vlrt.in/vc
▢️ *Demo Videos:*
https://www.vlrt.in/Vm

python

def is_strong(password):
    msg = 'Password must contain at least'
    if len(password) < 8:
        return False, msg + " 8 characters"

    has_upper = any(c.isupper() for c in password)
    has_lower = any(c.islower() for c in password)
    has_digit = any(c.isdigit() for c in password)
    special_chars = set("!@#$%^&*-_+=")
    has_special = any(c in special_chars for c in password)

    if not has_upper:
        return False, msg + " one uppercase letter."
    if not has_lower:
        return False, msg + " one lowercase letter."
    if not has_digit:
        return False, msg + " one digit."
    if not has_special:
        return False, msg + " one special char (!@#$%^&*-_+=)"

    return True, "Password is strong!"

password = input("Enter your password: ")
valid, message = is_strong(password)
print(message)

Enhanced Password Strength Checker

python

import re

def is_strong(password):
    """
    Check if a password is strong based on multiple criteria.
    Returns (is_valid, message) tuple.
    """
    # Define criteria and error messages
    criteria = [
        {
            'check': len(password) >= 8,
            'message': "at least 8 characters"
        },
        {
            'check': bool(re.search(r'[A-Z]', password)),
            'message': "one uppercase letter (A-Z)"
        },
        {
            'check': bool(re.search(r'[a-z]', password)),
            'message': "one lowercase letter (a-z)"
        },
        {
            'check': bool(re.search(r'[0-9]', password)),
            'message': "one digit (0-9)"
        },
        {
            'check': bool(re.search(r'[!@#$%^&*\-_+=]', password)),
            'message': "one special character (!@#$%^&*-_+=)"
        }
    ]
    
    # Check all criteria
    failed_checks = [criterion['message'] for criterion in criteria if not criterion['check']]
    
    if failed_checks:
        error_msg = "Password must contain:\n" + "\n".join(f"β€’ {msg}" for msg in failed_checks)
        return False, error_msg
    
    return True, "βœ… Password is strong!"

def get_password_strength_score(password):
    """
    Calculate a password strength score (0-100)
    """
    score = 0
    
    # Length score (max 25 points)
    length = len(password)
    if length >= 12:
        score += 25
    elif length >= 8:
        score += 15
    elif length >= 6:
        score += 5
    
    # Character variety score (max 75 points)
    checks = [
        bool(re.search(r'[A-Z]', password)),  # Uppercase
        bool(re.search(r'[a-z]', password)),  # Lowercase
        bool(re.search(r'[0-9]', password)),  # Digits
        bool(re.search(r'[!@#$%^&*\-_+=]', password)),  # Special chars
        len(set(password)) / len(password) > 0.7  # Character diversity
    ]
    
    score += sum(15 for check in checks if check)  # 15 points per met criteria
    
    return min(score, 100)

def suggest_strong_password():
    """
    Generate a strong password suggestion
    """
    import random
    import string
    
    # Define character sets
    uppercase = string.ascii_uppercase
    lowercase = string.ascii_lowercase
    digits = string.digits
    special_chars = "!@#$%^&*-_+="
    
    # Generate password with at least one of each type
    password = [
        random.choice(uppercase),
        random.choice(lowercase),
        random.choice(digits),
        random.choice(special_chars)
    ]
    
    # Add more random characters to reach 12 characters
    all_chars = uppercase + lowercase + digits + special_chars
    password.extend(random.choice(all_chars) for _ in range(8))
    
    # Shuffle the password
    random.shuffle(password)
    
    return ''.join(password)

def password_strength_checker():
    """
    Interactive password strength checker
    """
    print("πŸ” Password Strength Checker")
    print("=" * 40)
    print("Requirements:")
    print("β€’ At least 8 characters")
    print("β€’ Uppercase and lowercase letters")
    print("β€’ At least one digit")
    print("β€’ At least one special character (!@#$%^&*-_+=)")
    print("Type 'quit' to exit\n")
    
    while True:
        password = input("Enter your password: ").strip()
        
        if password.lower() in ['quit', 'exit', 'q']:
            print("Goodbye! πŸ‘‹")
            break
        
        if not password:
            print("Please enter a password!")
            continue
        
        # Check password strength
        is_valid, message = is_strong(password)
        strength_score = get_password_strength_score(password)
        
        print(f"\nπŸ“Š Password Analysis:")
        print(f"Strength Score: {strength_score}/100")
        
        if is_valid:
            print("βœ… " + message)
            if strength_score >= 80:
                print("πŸŽ‰ Excellent password!")
            elif strength_score >= 60:
                print("πŸ‘ Good password!")
            else:
                print("πŸ’ͺ Password meets minimum requirements")
        else:
            print("❌ Password is weak!")
            print(message)
        
        # Offer suggestion
        if not is_valid or strength_score < 60:
            suggest = input("\nWould you like a strong password suggestion? (y/n): ").lower()
            if suggest in ['y', 'yes']:
                suggested = suggest_strong_password()
                print(f"πŸ’‘ Suggested strong password: {suggested}")
                print("(Copy this password and use it securely)")
        
        print("-" * 40)

# Quick test function
def test_passwords():
    """
    Test various passwords
    """
    test_cases = [
        "weak",           # Too short
        "weakpassword",   # No uppercase, digits, or special
        "WeakPassword",   # No digits or special
        "Weak123",        # Too short, no special
        "Weak123!",       # Meets all criteria
        "VeryStrongPassword123!@#",  # Very strong
        "abc123",         # No uppercase, no special
        "ABC123!",        # No lowercase
    ]
    
    print("πŸ§ͺ Password Test Cases:")
    print("=" * 50)
    
    for password in test_cases:
        is_valid, message = is_strong(password)
        score = get_password_strength_score(password)
        status = "βœ… STRONG" if is_valid else "❌ WEAK"
        print(f"{password:25} -> {status} (Score: {score}/100)")
        if not is_valid:
            print(f"   Reasons: {message.split(':', 1)[1].strip()}")

if __name__ == "__main__":
    # Run interactive checker
    password_strength_checker()
    
    # Uncomment to run test cases
    # test_passwords()

Simple Version (Similar to Original)

python

import re

def is_strong(password):
    """
    Enhanced version of the original function with better error messages
    """
    if len(password) < 8:
        return False, "Password must contain at least 8 characters"
    
    checks = [
        (bool(re.search(r'[A-Z]', password)), "one uppercase letter (A-Z)"),
        (bool(re.search(r'[a-z]', password)), "one lowercase letter (a-z)"),
        (bool(re.search(r'[0-9]', password)), "one digit (0-9)"),
        (bool(re.search(r'[!@#$%^&*\-_+=]', password)), "one special character (!@#$%^&*-_+=)")
    ]
    
    missing = [msg for check, msg in checks if not check]
    
    if missing:
        error_msg = "Password must contain:\n" + "\n".join(f"β€’ {msg}" for msg in missing)
        return False, error_msg
    
    return True, "βœ… Password is strong!"

# Main program
if __name__ == "__main__":
    password = input("Enter your password: ")
    valid, message = is_strong(password)
    print(message)

Key Improvements:

  1. Better Error Messages: Shows all missing requirements at once
  2. Regex Validation: More efficient character checking
  3. Strength Scoring: Quantitative strength measurement (0-100)
  4. Password Suggestions: Generates strong password suggestions
  5. Interactive Interface: User-friendly command-line interface
  6. Testing Function: Built-in test cases
  7. Character Diversity: Checks for repeated characters
  8. Modular Design: Separate functions for different functionalities

Example Output:

text

πŸ” Password Strength Checker
========================================
Requirements:
β€’ At least 8 characters
β€’ Uppercase and lowercase letters
β€’ At least one digit
β€’ At least one special character (!@#$%^&*-_+=)
Type 'quit' to exit

Enter your password: weakpass

πŸ“Š Password Analysis:
Strength Score: 20/100
❌ Password is weak!
Password must contain:
β€’ one uppercase letter (A-Z)
β€’ one digit (0-9)
β€’ one special character (!@#$%^&*-_+=)

Would you like a strong password suggestion? (y/n): y
πŸ’‘ Suggested strong password: X7g!k9@Lp2$q

This enhanced version provides much more detailed feedback and helpful features while maintaining the same core functionality as the original program!

Similar Posts

  • Sets in Python

    Sets in Python A set in Python is an unordered collection of unique elements. Sets are mutable, meaning you can add or remove items, but the elements themselves must be immutable (like numbers, strings, or tuples). Key Characteristics of Sets: Different Ways to Create Sets in Python Here are various methods to create sets in…

  • re.sub()

    Python re.sub() Method Explained The re.sub() method is used for searching and replacing text patterns in strings. It’s one of the most powerful regex methods for text processing. Syntax python re.sub(pattern, repl, string, count=0, flags=0) Example 1: Basic Text Replacement python import re text = “The color of the sky is blue. My favorite color is blue too.” #…

  • Tuples

    In Python, a tuple is an ordered, immutable (unchangeable) collection of elements. Tuples are similar to lists, but unlike lists, they cannot be modified after creation (no adding, removing, or changing elements). Key Features of Tuples: Syntax: Tuples are defined using parentheses () (or without any brackets in some cases). python my_tuple = (1, 2, 3, “hello”) or (without…

  • Python Course content for kids

    Module 1: The Basics (Getting the Computer to Talk) Goal: Understand how to communicate with the computer and store information. Module 2: Making Decisions (Teaching the Computer to Think) Goal: Learn how to use logic to control the flow of a program. Module 3: Loops (Working Smarter, Not Harder) Goal: Understand how to automate repetitive…

  • Keyword-Only Arguments in Python and mixed

    Keyword-Only Arguments in Python Keyword-only arguments are function parameters that must be passed using their keyword names. They cannot be passed as positional arguments. Syntax Use the * symbol in the function definition to indicate that all parameters after it are keyword-only: python def function_name(param1, param2, *, keyword_only1, keyword_only2): # function body Simple Examples Example 1: Basic Keyword-Only Arguments…

Leave a Reply

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