Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

Build a Secure Password Strength Checker in Python

A Python function that evaluates password strength based on length and character diversity, returning Weak, Moderate, or Strong.

Easy Python 3.9+ Jun 27, 2026 Strings & text 1 views 0 copies

Python code

26 lines
Python 3.9+
import re

def password_strength(password: str) -> str:
    score = 0
    if len(password) >= 8:
        score += 1
    if re.search(r'[a-z]', password):
        score += 1
    if re.search(r'[A-Z]', password):
        score += 1
    if re.search(r'\d', password):
        score += 1
    if re.search(r'[!@#$%^&*(),.?":{}|<>]', password):
        score += 1

    if score <= 2:
        return "Weak"
    elif score == 3:
        return "Moderate"
    else:
        return "Strong"

if __name__ == "__main__":
    test_passwords = ["hello", "Password123!", "weak", "Str0ng!Pass"]
    for pwd in test_passwords:
        print(f"'{pwd}' -> {password_strength(pwd)}")

Output

stdout
'hello' -> Weak
'Password123!' -> Strong
'weak' -> Weak
'Str0ng!Pass' -> Strong

How it works

The function assigns one point for each of five criteria: length >=8, lowercase, uppercase, digit, and a special character. The score determines the strength rating. Using re.search with character classes makes checks concise and readable. This approach gives immediate feedback without external libraries.

Common mistakes

  • Forgetting to check for whitespace or empty strings, which would score 0 and return Weak.
  • Using a weak regex for special characters that misses common symbols like `@` or `#`.
  • Not handling Unicode or non-ASCII characters, which may cause false positives.

Variations

  1. Use a single regex with lookaheads for a one-pass check.
  2. Add a blacklist check against common weak passwords.

Real-world use cases

  • Enforcing minimum password strength during user registration in a web app.
  • Validating password reset tokens to prevent reuse of weak passwords.
  • Auditing existing stored hashes by rechecking strength of known plaintexts.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

Related tutorials and quizzes for this topic.