Skip to content
Python project #07Beginner

Password Strength Checker

Score passwords from 0 to 100 with explanations — length, character variety, common passwords, leetspeak, sequences and repeats — and generate strong ones.

Estimated time
~2 hours to build
Files
4 files · 271 lines
Technologies
Python 3, secrets, string, re

Introduction

Weak passwords remain one of the biggest causes of account break-ins. This tool explains why a password is weak and generates strong ones with Python's secrets module, which is designed for security.

Problem statement

For 'check <password>', score the password from 0 to 100 based on length and the four character classes, cap it if it is a common password (also after undoing leetspeak such as P@ssw0rd), and subtract points for keyboard or alphabet sequences and triple repeats. Show a verdict and explanations. For 'generate <length>', create a password with at least one character from each class using secrets; 'generate <length> seed <n>' makes a repeatable demo password that is clearly labelled as unsafe.

Objectives

  • Combine several rules into a score
  • Use str.translate for leetspeak normalisation
  • Use regular expressions to detect repeats
  • Understand why secrets, not random, is used for passwords

Features

  • 0–100 score with a verdict
  • Explanations for every weakness
  • Common-password and leetspeak detection
  • Sequence and repeat detection
  • Secure generator guaranteeing all character classes

Concepts demonstrated

  • Scoring heuristics
  • String methods and translation tables
  • Cryptographically secure randomness
  • Input masking

System architecture

score computes points from length and character classes, then applies penalties using has_sequence, a regex for repeated characters and a common-password set checked against a leetspeak-normalised copy. verdict maps points to a label. generate picks one character from each pool, fills the rest and shuffles, using secrets unless a seeded random.Random is given for demos.

Folder structure

TextProject tree
password-checker/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

117 lines
Pythonmain.py
"""Password Checker and Generator.
Commands:
check <password> score a password from 0 to 100 and explain why
generate <length> create a strong password with the secrets module
generate <length> seed <n> repeatable demo password (NOT for real use)
quit
"""
import random
import re
import secrets
import string
import sys
COMMON = {"password", "123456", "12345678", "qwerty", "abc123", "111111", "letmein", "welcome", "admin", "iloveyou",
"monkey", "dragon", "sunshine", "football", "india123", "password1"}
LEET = str.maketrans({"@": "a", "4": "a", "3": "e", "1": "i", "!": "i", "0": "o", "$": "s", "5": "s", "7": "t"})
SEQUENCES = ["abcdefghijklmnopqrstuvwxyz", "0123456789", "qwertyuiop", "asdfghjkl", "zxcvbnm"]
def ask(prompt: str) -> str | None:
try:
line = input(prompt)
except EOFError:
print()
return None
if not sys.stdin.isatty():
print(line)
return line.rstrip("\n")
def has_sequence(pw: str, length: int = 4) -> bool:
low = pw.lower()
for seq in SEQUENCES:
for i in range(len(seq) - length + 1):
chunk = seq[i:i + length]
if chunk in low or chunk[::-1] in low:
return True
return False
def score(pw: str) -> tuple[int, list[str]]:
notes: list[str] = []
classes = [any(c.islower() for c in pw), any(c.isupper() for c in pw), any(c.isdigit() for c in pw),
any(c in string.punctuation for c in pw)]
points = min(len(pw), 20) * 3 + sum(classes) * 10
if len(pw) < 8:
notes.append("too short: use at least 12 characters")
elif len(pw) < 12:
notes.append("length is fair; 12+ characters is better")
missing = [name for name, ok in zip(["lower-case", "upper-case", "digits", "symbols"], classes) if not ok]
if missing:
notes.append("add " + ", ".join(missing))
base = re.sub(r"[^a-z]", "", pw.lower().translate(LEET))
if pw.lower() in COMMON or base in COMMON:
points = min(points, 5)
notes.append("this is one of the most common passwords")
if has_sequence(pw):
points -= 15
notes.append("contains a keyboard or alphabet sequence")
if re.search(r"(.)\1\1", pw):
points -= 10
notes.append("repeats the same character three times")
return max(0, min(points, 100)), notes
def verdict(points: int) -> str:
return "very weak" if points < 30 else "weak" if points < 50 else "fair" if points < 70 else "strong" if points < 90 else "very strong"
def generate(length: int, rng=None) -> str:
"""Guarantee one character of each class, fill the rest, then shuffle."""
if not 8 <= length <= 64:
raise ValueError("length must be between 8 and 64")
pick = rng.choice if rng else secrets.choice
pools = [string.ascii_lowercase, string.ascii_uppercase, string.digits, "!@#$%^&*-_=+?"]
chars = [pick(pool) for pool in pools] + [pick("".join(pools)) for _ in range(length - 4)]
(rng or secrets.SystemRandom()).shuffle(chars)
return "".join(chars)
def main() -> None:
print("Password Checker - commands: check <password>, generate <length> [seed <n>], quit")
while True:
line = ask("> ")
if line is None or line.strip().lower() == "quit":
break
command, _, rest = line.strip().partition(" ")
command = command.lower()
if command == "check" and rest:
points, notes = score(rest)
masked = rest[0] + "*" * (len(rest) - 2) + rest[-1] if len(rest) > 2 else "*" * len(rest)
print(f" {masked}: {points}/100 ({verdict(points)})")
for note in notes:
print(f" - {note}")
elif command == "generate":
parts = rest.split()
if parts and not parts[0].isdigit():
print(f" Error: length must be a whole number, not '{parts[0]}'")
continue
try:
length = int(parts[0]) if parts else 16
rng = random.Random(int(parts[2])) if len(parts) == 3 and parts[1] == "seed" else None
password = generate(length, rng)
except ValueError as error:
print(f" Error: {error}")
continue
points, _ = score(password)
label = "demo (seeded, do not use)" if rng else "use it"
print(f" {password} -> {points}/100 ({verdict(points)}), {label}")
else:
print(" Unknown command. Try: check <password>, generate <length>, quit")
if __name__ == "__main__":
main()

What each file does

main.py
The whole program: data classes, validation, the command loop and the report.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Password Checker - commands: check <password>, generate <length> [seed <n>], quit
> check 123456
1****6: 0/100 (very weak)
- too short: use at least 12 characters
- add lower-case, upper-case, symbols
- this is one of the most common passwords
- contains a keyboard or alphabet sequence
> check P@ssw0rd
P******d: 5/100 (very weak)
- length is fair; 12+ characters is better
- this is one of the most common passwords
> check sunshine2026
s**********6: 56/100 (fair)
- add upper-case, symbols
> check abcd1234XY
a********Y: 45/100 (weak)
- length is fair; 12+ characters is better
- add symbols
- contains a keyboard or alphabet sequence
> check aaaPython!9
a*********9: 63/100 (fair)
- length is fair; 12+ characters is better
- repeats the same character three times
> check Tr!cky-Monsoon-42
T***************2: 91/100 (very strong)
> check correct horse battery staple
c**************************e: 70/100 (strong)
- add upper-case, digits, symbols
> generate 16 seed 7
m#6?ghj3Bk&Ul=Ee -> 88/100 (strong), demo (seeded, do not use)
> generate 4 seed 1
Error: length must be between 8 and 64
> generate twelve
Error: length must be a whole number, not 'twelve'
> help
Unknown command. Try: check <password>, generate <length>, quit
> quit
Input
check 123456
check P@ssw0rd
check sunshine2026
check abcd1234XY
check aaaPython!9
check Tr!cky-Monsoon-42
check correct horse battery staple
generate 16 seed 7
generate 4 seed 1
generate twelve
help
quit

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • 123456 scores 0 and P@ssw0rd is recognised as the common password 'password'.
  • abcd1234XY loses points for alphabet and number sequences.
  • Tr!cky-Monsoon-42 scores 91 (very strong); a length of 4 and 'twelve' are rejected by generate.

Common errors

Generated passwords are predictable

Use secrets.choice and secrets.SystemRandom, never the random module, for real passwords.

P@ssw0rd passes as strong

Normalise leetspeak with str.translate before comparing with the common list.

Possible improvements

  • Check passwords against a larger breach list
  • Estimate crack time from the number of possible combinations
  • Generate memorable passphrases from a word list

Additional challenges

  1. 1Detect dates such as 2026 or 27112026 inside passwords.
  2. 2Add an option to exclude look-alike characters (0/O, 1/l).
  3. 3Score with entropy in bits instead of points.

Built and tested it yourself? Mark it to update your dashboard.