Validate Password Strength in Python
Check length and character groups with Python regex searches. This beginner password-policy exercise explains matches and why passing is not proof of safety.
1# Program to validate password strength23import re45password = input("Enter a password: ")67length_ok = len(password) >= 88has_upper = re.search(r"[A-Z]", password) is not None9has_lower = re.search(r"[a-z]", password) is not None10has_digit = re.search(r"[0-9]", password) is not None11has_special = re.search(r"[^A-Za-z0-9]", password) is not None1213if length_ok and has_upper and has_lower and has_digit and has_special:14 print("Strong password")15else:16 print("Weak password")
Output
Strong password
The sample satisfies the length requirement and all four character-presence tests.
In this one
- Use re.search for presence checks
- Convert match results with is not None
- Combine independent policy requirements
How it works
- 1
Read password and test its length.
- 2
Search for uppercase, lowercase, digit, and outside-range characters.
- 3
Require all five Booleans before printing the policy success label.
Edge cases
Too short
Enter A@1.
Character variety is present, but length_ok is False.
Space as special
Use a password containing a space.
The negated character class counts that space as a special character.
What's going on
Abc@1234 passes this policy: eight characters, an uppercase letter, a lowercase letter, a digit, and a special character. That is what the label Strong password means here, not a guarantee that the password is safe.
Each re.search looks for at least one matching character anywhere in the text. It returns a match object or None. The expression is not None turns that result into an explicit Boolean, then and requires all five checks.
The character classes are ASCII-oriented: [A-Z], [a-z], and [0-9]. The negated class counts anything outside those ranges as special, including spaces and non-ASCII letters. Length and character variety alone do not detect reused, leaked, or easily guessed passwords. Use sample text rather than a real credential while experimenting.
After this program
If the idea is still fuzzy, read Day 8: Conditional Statements in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 conditional programs, or see every topic on Python exercises.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does re.search return when no match exists?
Pick an answer to check it.
Question 2
Does passing this policy prove security?
Pick an answer to check it.
Questions people ask
What does re.search return when no match exists?
It returns None, so is not None becomes False.
Does passing this policy prove security?
No. It checks only these composition rules, not guessability, reuse, or leaks.
Why use is not None rather than identity tests on strings?
None is a singleton checked by identity; the password text itself is compared or searched by value.