Mini-Project: Password Strength Checker
any() with list comprehensions, and the rule-collection pattern that validators use.Before you start
#What you'll build
weak, medium, or strong) along with a list of human-friendly hints for what's missing.Sample interaction
Enter a password: hello
Strength: weak
Missing:
- at least 8 characters
- an uppercase letter
- a digit
- a special character
Enter a password: Hunter2!
Strength: strong
No issues. Good to go.
#What you'll learn
After this lesson, you will be able to:
- Check the properties of a string with len(), .isupper(), .isdigit() and friends
- Ask 'does this contain at least one X?' with any() and a list comprehension
- Score a set of rules and turn the score into a label a person can read
#Step 1: Length check
len(password) >= 8 is a True/False expression you can use directly.def is_long_enough(password):
return len(password) >= 8
print(is_long_enough("hi")) # False
print(is_long_enough("Hunter2!")) # TrueTiny function, big habit — one rule per function, each returning a boolean. That's a common structure for validators.
What does "Hello".isupper() return?
.isupper() returns True only when ALL the alphabetic characters in the string are uppercase. "Hello" has lowercase letters (e, l, l, o), so it's False. Common misconception: thinking it checks if the string CONTAINS any uppercase. To check that, you need any([c.isupper() for c in s]). Same pattern applies to .islower(), .isdigit(), .isalpha() — they all check "is ALL of it this kind?", not "does it contain?".What does `len('Hunter2!')` return?
#Step 2: Check for an uppercase letter
'A'.isupper() returns True. But how do you check the whole password for "contains AT LEAST ONE uppercase letter"? Use any() with a list comprehension.def has_upper(password):
return any([c.isupper() for c in password])
print(has_upper("hello")) # False
print(has_upper("Hello")) # Trueany(...) returns True if at least one item in the list is truthy. The list comprehension [c.isupper() for c in password] builds a True/False for each character, so any() over it answers "is at least one of them True?". (A form without the square brackets stops at the first True instead of building the whole list; it comes with generators, later in this track.)What does any([]) return?
What does `any([c.isdigit() for c in 'abc'])` return?
#Step 3: Build the full checker
any pattern for digits, lowercase, and special characters. Special characters are anything not alphanumeric — the easiest check is not c.isalnum().def check_password(password):
rules = {
"at least 8 characters": len(password) >= 8,
"an uppercase letter": any([c.isupper() for c in password]),
"a lowercase letter": any([c.islower() for c in password]),
"a digit": any([c.isdigit() for c in password]),
"a special character": any([not c.isalnum() for c in password]),
}
return rules
print(check_password("Hunter2!"))
# {'at least 8 characters': True, 'an uppercase letter': True, ...}The dict maps "human description" to "rule passes?". Now you can ask: how many rules pass? Which ones failed?
#Step 4: Score and label
Count the rules that pass. Use that count to assign a strength label.
def strength(password):
rules = check_password(password)
score = sum(rules.values()) # True is 1, False is 0
if score <= 2:
return "weak"
if score == 3 or score == 4:
return "medium"
return "strong"
print(strength("hi")) # weak
print(strength("Hello12")) # medium
print(strength("Hunter2!")) # strongsum(rules.values()) works because Python treats True as 1 and False as 0 in arithmetic. Then a simple ladder maps the score to a label.What does this print? flags = [True, False, True, True, False] print(sum(flags))
True is literally 1 and False is literally 0 for arithmetic purposes (bool is a subclass of int). So sum([True, False, True, True, False]) is 1 + 0 + 1 + 1 + 0 = 3. This is hugely useful: any time you want to COUNT how many things are true, sum([condition for item in items]) is the Pythonic way. Examples: sum([score >= 60 for score in grades]) counts passing grades, sum([c.isupper() for c in s]) counts uppercase letters.#Step 5: Helpful "what's missing" feedback
The point of a strength meter is to help the user fix it. Return the list of rules that DIDN'T pass.
def feedback(password):
rules = check_password(password)
missing = [name for name, passed in rules.items() if not passed]
label = strength(password)
return label, missing
label, missing = feedback("hello")
print("Strength:", label)
if missing:
print("Missing:")
for item in missing:
print(f"- {item}")
else:
print("No issues. Good to go.")That's the entire meter — five small functions, each doing one thing, composed into a real user-facing tool.
#Now build it yourself
In the browser,input()cannot pause and wait for you. Type the passwords into the Input box under the code, one per line (for examplehello, thenHunter2!, then a blank line to stop). Your typed answers are not echoed, so the output shows each prompt followed by the result.
Full password strength meter with feedback
Write `strength_report(password)` that returns a tuple (label, missing_list) where label is 'weak'/'medium'/'strong' and missing_list is a list of human-readable strings naming the rules that failed. Use 5 rules: length >= 8, has upper, has lower, has digit, has special character (anything not alphanumeric). Score: 0-2 rules = weak, 3-4 = medium, 5 = strong. Type the passwords, one per line, in the Input box above Run.
Enter a password: hello
Strength: weak
Missing:
- at least 8 characters
- an uppercase letter
- a digit
- a special character
Enter a password: Hunter2!
Strength: strong
No issues. Good to go.This code calls input(). Python here can't pause to ask you, so type the answers below before running — one value per line, in the order the program asks for them.
#Now make it your own
Try one of these variations:
- Banned-password list. Maintain a set of common bad passwords ('password', '123456', 'qwerty'). If the input is in the set, force the label to 'weak' regardless of score.
- Length tiers. Award an extra point for 12+ characters and another for 16+. A long passphrase with no special characters should still score 'strong'.
- Entropy estimate — compute a rough entropy in bits:
import math; bits = len(password) * math.log2(charset_size). Print "Estimated time to crack: ..." based on entropy bands.
#What's next
try/except so your code survives bad input instead of crashing.