Reject a password that is too short.
What to build
A function that raises an error, and a caller that handles it.
Requirements
- Write
check(password), which raisesValueErrorif the password has fewer than 8 characters. - For each line, print
ok, ortoo short.
Input
The first line has n. Each of the next n lines is a password.
Output
One line per password.
Constraints
n is from 1 to 50.
Example
Input:
2
secret
longenough
Output:
too short
ok
Why it works
The function only reports the problem, and leaves it to the caller to decide what to say about it.
Examples
Example 1 · Input
2 secret longenough
Expected output
too short ok
Example 2 · Input
1 12345678
Expected output
ok
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Write if len(password) < 8: and raise ValueError inside it.
Hint 2
The caller catches it with except ValueError.
Solution
Show one correct solution (try it yourself first)
def check(password):
if len(password) < 8:
raise ValueError("password must have at least 8 characters")
n = int(input())
for _ in range(n):
try:
check(input())
print("ok")
except ValueError:
print("too short")