If statement printing all conditions

Question:

I’m trying to build a password strength checker function.

def passwordStrengthCheck():
  password = "Passw0rd!"
  lower = any(letter.islower() for letter in password)
  upper = any(letter.isupper() for letter in password)
  num = any(char.isdigit() for char in password)
   
  if len(password) < 8:
      print("Password does not meet requirements.")
  elif not lower:
      print("Password does not meet requirements.")
  elif not upper:
      print("Password does not meet requirements.")
  elif not num:
      print("Password does not meet requirements.")
  else:
      for char in password:
          if not (char.isalpha() or char.isdigit() or char == ' '):
              print("Password is accepted.")
          else:
            print("Password does not meet requirements.") 

passwordStrengthCheck()

The output I am getting is this

Password does not meet requirements.
Password does not meet requirements.
Password does not meet requirements.
Password does not meet requirements.
Password does not meet requirements.
Password does not meet requirements.
Password does not meet requirements.
Password does not meet requirements.
Password is accepted.

I can’t figure out why I am getting every option plus some extra as an output. I was hoping to get an output that the password either does or doesn’t meet requirements.

Asked By: Makayla Galbraith

||

Answers:

Instead of checking only one character each time and printing a result based on that, check ALL the characters before deciding if the password meets the requirements.

Here, you should check if any character in the string is not alphanumeric or a space, in which case the password is accepted. In other words, if all of the characters are alphanumeric or spaces, then the password does not meet the requirements.

# other checks...
elif all(char.isalpha() or char.isdigit() or char == ' ' for char in password):
  print("Password does not meet requirements.")
else:
  print("Password is accepted")
Answered By: Unmitigated

It looks like the problem with your code is in the last else statement. Inside that else statement, you are checking each character of the password and printing "Password does not meet requirements." for every character that is not a letter or a digit or a space. So, if your password has 8 characters, you will get 8 outputs from that else statement, and only the last one will say "Password is accepted."

To fix this, you can remove the else statement and move the final "Password is accepted." print statement outside of the loop. Here is the modified code:

def passwordStrengthCheck():
    password = "Passw0rd!"
    lower = any(letter.islower() for letter in password)
    upper = any(letter.isupper() for letter in password)
    num = any(char.isdigit() for char in password)

    if len(password) < 8:
        print("Password does not meet requirements.")
    elif not lower:
        print("Password does not meet requirements.")
    elif not upper:
        print("Password does not meet requirements.")
    elif not num:
        print("Password does not meet requirements.")
    else:
        for char in password:
            if not (char.isalpha() or char.isdigit() or char == ' '):
                print("Password does not meet requirements.")
                break
        else:
            print("Password is accepted.")

passwordStrengthCheck()

In this modified version, the else statement is now part of the for loop, but it only prints "Password does not meet requirements." and breaks out of the loop if it finds a character that is not a letter, digit, or space. If the loop completes without finding any such character, the else statement following the loop will be executed and print "Password is accepted."

Here’s another example of a password strength checker function:

def password_strength(password):
    """Check the strength of a password"""

    # Define character sets
    lowercase = "abcdefghijklmnopqrstuvwxyz"
    uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    numbers = "0123456789"
    symbols = "!@#$%^&*()-_=+[{]}\|;:'",<.>/?"
    
    # Initialize strength score and complexity flag
    strength = 0
    is_complex = False
    
    # Check password length
    if len(password) >= 8:
        strength += 1
    
    # Check for uppercase letters
    if any(char in uppercase for char in password):
        strength += 1
    
    # Check for lowercase letters
    if any(char in lowercase for char in password):
        strength += 1
    
    # Check for numbers
    if any(char in numbers for char in password):
        strength += 1
    
    # Check for symbols
    if any(char in symbols for char in password):
        strength += 1
    
    # Check for complexity (i.e. three or more character sets used)
    if strength >= 3:
        is_complex = True
    
    # Return strength and complexity
    return (strength, is_complex)

This function takes a password as input and returns a tuple containing the password strength score (an integer between 0 and 5) and a boolean indicating whether the password is considered complex (i.e. contains characters from at least three of the four defined character sets).

Here’s an example usage of the function:

password = "MyS3cur3P@ssw0rd"
strength, is_complex = password_strength(password)
print(f"Password strength: {strength}/5")
print(f"Is complex: {is_complex}")

This would output:

Password strength: 5/5
Is complex: True
Answered By: Drof
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.