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
Python
defcheck(password):has_lower=has_upper=has_digit=has_special=Falseforchinpassword:ifch.islower():has_lower=Trueelifch.isupper():has_upper=Trueelifch.isdigit():has_digit=Trueelifchin"$#@":has_special=Trueproblems=[]ifnot5<=len(password)<=15:problems.append("length must be 5-15")ifnothas_lower:problems.append("needs a lowercase letter")ifnothas_upper:problems.append("needs an uppercase letter")ifnothas_digit:problems.append("needs a digit")ifnothas_special:problems.append("needs one of $#@")return"Valid password"ifnotproblemselse"Invalid: "+", ".join(problems)forpwin["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.