BryanL
BryanL

Reputation: 35

Check that password contains at least two uppercase and two lowercase letters

The requirement is 2, but its outcome is 6. How can I solve the problem?

def is_password_valid(password):
    requirements = 0

    upper_case = []
    for j in password:
        if j.isupper():
            upper_case.append(j)
            if len(upper_case) > 1:
                requirements += 1

    lower_case = []
    for j in password:
        if j.islower():
            lower_case.append(j)
            if len(lower_case) > 1:
                requirements += 1

    print(requirements)

password = 'PAssword1$'
is_password_valid(password)

Upvotes: 1

Views: 1102

Answers (2)

S.N
S.N

Reputation: 5140

If you're after a concise approach you may find the following helpful.

sum_of_ucase = sum(1 for c in password if c.isupper()))

Upvotes: 1

Jerm1812
Jerm1812

Reputation: 26

The reason your requirements turn out to be 6 is that the way you have your loops set up. The second time your upper case loop it adds one. The second through the sixth time because every time the loop runs the length of lower_case is greater than one.

You could change it so that it breaks out by adding a break statement right after your requirements += 1 statement.

You can also use regex like this:

import re

pattern = re.compile("(?=(.*[a-z]){2,})(?=(.*[A-Z]){2,})")
string = "pasSwSrd"
if pattern.match(string):
    print("Password meets requirements!")
else:
    print("Password does not meet requirements!")

Upvotes: 1

Related Questions