Can this be shortened/improved? I'm trying to make a password checker in python.
Could the if's be put into a for loop? And if so, how?
pw = input("Enter password to test: ")
caps = sum(1 for c in pw if c.isupper())
lower = sum(1 for c in pw if c.islower())
nums = sum(1 for c in pw if c.isnumeric())
scr = ['weak', 'medium', 'strong']
r = [caps, lower, nums]
if len(pw) < 6:
print("too short")
elif len(pw) > 12:
print("too long")
if caps >= 1:
if lower >= 1:
if nums >= 1:
print(scr[2])
elif nums < 1:
print("your password is " + scr[1])
elif lower < 1:
print("your password strength is " + scr[0])
elif caps < 1:
print("your password strength is " + scr[1])
Thanks for any suggestions :D
can be:
can be:
The most significant improvement: The bottom
if
/elif
block can be completely removed by doingExplanation:
map(bool,[caps,lower,nums])
accumulates how many times each ofcaps,lower,nums
is non-zero. Adding them up withsum
gives you your "strength", which you've conveniently already put into a list, which can be accessed by index.All of these improvements leverage the concept of "falsiness" in python, otherwise known as an object's value in a boolean context. Generally empty and zero things are
False
, and summing booleans is equivalent to adding ones and zeroes, so there you go.Of course, it doesn't seem that you're doing anything with the counts of upper/lower/nums other than checking if they're nonzero. So a cleanup would just be
and then
I would fix that nested if statement.
I'll ignore the general question, "can this code be shortened or improved", because that's a question for Code Review. But you've also got a specific question in there:
They could, but you'd have to turn them into something that can be put inside an iterator, like functions, and I really don't think you want to in this case.
Let's start with a simpler example, with just a linear series of checks:
You could instead put the check conditions in some encoded data form, and replace the
if check(…)
with a data-driven check on the conditions. For example:But I think that's even less readable. There are plenty of use cases where this kind of thing makes sense—e.g., imagine you wanted to evaluate 40 polynomials for each value of x; you'd store each polynomial as a list of coefficients, and have generic "evaluate polynomial" logic like this. But this isn't one of those cases.
Either way, that's already pretty ugly. And if you want nested checks, you're going to need a nested structure, which you probably want to process recursively.