Python Practice › Loop Programs › Program 57
Validate a password
Write a Python program to check a password: at least one lowercase letter, one uppercase letter, one digit, one of $ # @, and 5 to 15 characters long.
Input
"Abc@1234", "abc123", "Ab1$"
Output
Abc@1234 -> Valid password abc123 -> Invalid: needs an uppercase letter, needs one of $#@ Ab1$ -> Invalid: length must be 5-15
Approach
- Loop over the characters once, recording which kinds were seen.
- Check all rules at the end and list any that failed.
Solution
def check(password): has_lower = has_upper = has_digit = has_special = False for ch in password: if ch.islower(): has_lower = True elif ch.isupper(): has_upper = True elif ch.isdigit(): has_digit = True elif ch in "$#@": has_special = True problems = [] if not 5 <= len(password) <= 15: problems.append("length must be 5-15") if not has_lower: problems.append("needs a lowercase letter") if not has_upper: problems.append("needs an uppercase letter") if not has_digit: problems.append("needs a digit") if not has_special: problems.append("needs one of $#@") return "Valid password" if not problems else "Invalid: " + ", ".join(problems) for pw in ["Abc@1234", "abc123", "Ab1$"]: print(pw, "->", check(pw))Output
Abc@1234 -> Valid password abc123 -> Invalid: needs an uppercase letter, needs one of $#@ Ab1$ -> Invalid: length must be 5-15
Line by line
Line 2
Four flags start as False.
Lines 3-11
One pass over the password sets the flags.
Lines 12-22
Each rule adds a readable reason when it fails, so the user knows what to fix.
Learn the concept
New to this topic? Read the lesson, then come back.