Why does my for loop not check every character?

184 views Asked by At

So I'm a bit of a beginner at python and I cant for the life of me figure out why it wont check and add on for every letter

def howstrong (password):
    points = len(password)
    charactersallowed = ["!", "$", "%", "^", "&", "*", "(", ")", "-", "_", "=", "+"]

    for ch in password:
        if ch.isupper():
            points= points+5
        elif ch.islower():
            points = points+5
        elif ch.isdigit():
            points = points+5
        elif ch in charactersallowed:
            points= points+5
        else:
            points = points+0
        return points

If I input a password of Password! into my code it tells me my points are 14 but for this password it should be 24? Below I will add the rest of my code but I doubt that its in that part and I believe that there's an error in my for loop somewhere.

def checkingmain():

    while 1:
        p = input("\nEnter password: ")
        if len(p) < 8 or len(p) > 24:
            print("Password must be 6 to 12 characters.")
        elif input("Re-enter password: ") != p:
            print("Passwords did not match. Please try again.")

        else:
            score= howstrong(p)
            if not score:
                print("Invalid character detected. Please try again.")

            else:
                if score <= 0:
                    print("your password is weak",score)
                elif score>0 and score<20:
                    print("your password is medium",score)
                else:
                    print("your password is strong",score)
            break

I'd appreciate if someone would get back to me with an understandable solution for a somewhat python beginner.

3

There are 3 answers

2
Daniel Roseman On

It only ever checks the first character, because you return inside the loop. Move your return statement back one indent, so it is not inside the for loop.

0
Bhawan On

The return statement is inside the for loop , so when your program reaches the end of the for loop for the first time, it simply returns from the function, so your for loop is terminated. A little change in your code like shown below will help you.

for ch in password:
    if ch.isupper():
        points= points+5
    elif ch.islower():
        points = points+5
    elif ch.isdigit():
        points = points+5
    elif ch in charactersallowed:
        points= points+5
    else:
        points = points+0
return points

Hope it helps !

0
Daniel Ojeda On

Since you have your return statement inside the loop, it only runs the loop one time before returning from the function. If you move your return statement back one tab it should work