1

I'm trying to write a Python program that prompts the user for a password. It must meet the following requirements:

  1. no less than 6 characters in length
  2. no more than 12 characters in length
  3. at least 1 numerical digit
  4. at least 1 alphabetical character
  5. no spaces

I can get through requirements 1-3, but as soon as I put in requirement 4, it stops working. I haven't even gotten to requirement 5 because I'm currently stuck. Any help is greatly appreciated! TIA!

Here is my code:

# --- Main ----------

def main():
    
    #display student info
    studentInfo()

    #display welcome message
    welcomeMsg()

    #prompt user for a password
    passWord = input("\nPlease create a password:\n")

    #call function for password length validation
    passWord = correctPW(passWord)

# --- Functions ----------

#student info
def studentInfo():
    print("\nName:\tNAME")
    print("Class:\tCMIS102")
    print("Date:\t26 July 2022")

#welcome message
def welcomeMsg():
    print("\nThis program will prompt the user to enter a password with the following requirements:")
    print("\t- No less than 6 characters in length")
    print("\t- No more than 12 characters in length")
    print("\t- No spaces")
    print("\t- At least one numerical digit")
    print("\t- At least one alphabetical character")

#validate password requirements
def correctPW(passWord):

    #check for minimum character requirement
    while (len(passWord) < 6) or (len(passWord) > 12):
        print("\nSorry! Your password is invalid.")
        print("It must be no less than 6 characters and no more than 12 characters in length.")
        passWord = input("\nPlease create a password:\n")

    #check for one numerical digit and alphabetical character requirement
    while (passWord.isdigit() < 1):
        print("\nSorry! Your password is invalid.")
        print("It must contain at least one numerical digit.")
        passWord = input("\nPlease create a password:\n")
        
    while (passWord.isalpha() < 1):
        print("\nSorry! Your password is invalid.")
        print("It must contain at least one alphabetical character.")
        passWord = input("\nPlease create a password:\n")

    #display if all password requirements are met
    if (len(passWord) >= 6) and (len(passWord) <= 12) and (passWord.isdigit() >= 1) and (passWord.isalpha() >= 1):
        print("\nCongratulations! Your password is valid!")
   
# --- Execute ----------

main()
4
  • What do you think passWord.isdigit() < 1, passWord.isalpha() < 1, and the rest are doing? Commented Jul 26, 2022 at 20:40
  • Ye, as Matt pointed out, those aren't doing what you think they're doing. Look up any, any(x.isalpha() for x in pswd) is probably what you want. Commented Jul 26, 2022 at 20:43
  • isdigit will check that all characters are digits and return True/False. isalpha will always return False if isdigit returns True. Commented Jul 26, 2022 at 20:44
  • I understand now! Thanks! The instructor told us to use isdigit and isalpha to check for the requirements. I dumbly went with it instead of validating what they actually did. Commented Jul 26, 2022 at 21:00

3 Answers 3

5

The isdigit function will return True if all of the char in the password be numbers, like '65' or '1235' but if in the password, the user has any char near the numbers, like 'asdf3567' or '1a2b3c4d' or etc, it will return False, so this condition password.isdigit() < 1 is not a good condition

The isalpha function will return True if all of the char in the password be alphabets, like 'abc' or 'simplepassword' but if in the password, user has any char near the alphabets, like 'asdf3567' or '1a2/$b3c4d' or etc, it will return False, so this condition password.isalpha() < 1 is not a good condition

Sign up to request clarification or add additional context in comments.

3 Comments

Ah! I see now! I wonder why the instructor gave us a hint to use those in the assignment instructions...
Dear @JessicaG. , you can use them by combining a for loop and any function, something like: if any(c.isdigit() for c in password) and ...
Thank you! This made sense and I was able to finish my assignment.
3

str.isdigit(): Return True if all characters in the string are digits and there is at least one character, False otherwise.

—https://docs.python.org/3/library/stdtypes.html#str.isdigit

Therefore, if passWord is (for example) "a1", then passWord.isdigit() will return False. You can, however, use it for each characters in the string, by using list (or generator) comprehension.

def check(password):
    if not (6 <= len(password) <= 12):
        print("Length must be between 6 and 12 (inclusive).")
        return False
    if any(char.isdigit() for char in password):
        print("Must have a digit.")
        return False
    if any(char.isalpha() for char in password):
        print("Must have an alphabet.")
        return False
    if any(char.isspace() for char in password):
        print("Must not have a space.")
        return False
    return True

while True:
    password = input("Enter a password: ")
    if check(password):
        break

print(f"Your password is: {password}... Oops, I said it out loud!")

If you want the actual number of digits in the password, you can use sum instead of any:

if sum(char.isdigit() for char in password) < 1:

1 Comment

You are an absolute lifesaver! Thank you so much!!
1

Based on help(str) in python shell:

isdigit(self, /) Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isalpha(self, /) Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

So in lines:

while (passWord.isdigit() < 1): ...

while (passWord.isalpha() < 1): ...

passWord.isdigit() and passWord/.isalpha() even for your valid inputs are always False and for both of them < 1 will be True and this will cause an infinite loop in your program.

I applied two new functions to your code to check if user inputs a valid pass you expected or not.

# --- Main ----------

def main():
    
    #display student info
    studentInfo()

    #display welcome message
    welcomeMsg()

    #prompt user for a password
    passWord = input("\nPlease create a password:\n")

    #call function for password length validation
    passWord = correctPW(passWord)

# --- Functions ----------

#student info
def studentInfo():
    print("\nName:\tJessica Graeber")
    print("Class:\tCMIS102")
    print("Date:\t26 July 2022")

#welcome message
def welcomeMsg():
    print("\nThis program will prompt the user to enter a password with the following requirements:")
    print("\t- No less than 6 characters in length")
    print("\t- No more than 12 characters in length")
    print("\t- No spaces")
    print("\t- At least one numerical digit")
    print("\t- At least one alphabetical character")


def containsLetterAndNumber(input_password):
    return input_password.isalnum() and not input_password.isalpha() and not input_password.isdigit()

def containsBlankSpace(input_password):
    return (' ' in input_password)

#validate password requirements
def correctPW(passWord):

    #check for minimum character requirement
    while (len(passWord) < 6) or (len(passWord) > 12):
        print("\nSorry! Your password is invalid.")
        print("It must be no less than 6 characters and no more than 12 characters in length.")
        passWord = input("\nPlease create a password:\n")

    #check for one numerical digit and alphabetical character requirement      
    while not containsLetterAndNumber(passWord):
        print("\nSorry! Your password is invalid.")
        print("It must contain at least one alphabetical character and one numerical digit.")
        passWord = input("\nPlease create a password:\n")
    
    while containsBlankSpace(passWord):
        print("\nSorry! Your password is invalid.")
        print("It shouldn't have any blank space in it.")
        passWord = input("\nPlease create a password:\n")


    # display if all password requirements are met
    if (len(passWord) >= 6) and (len(passWord) <= 12) and containsLetterAndNumber(passWord) and (not containsBlankSpace(passWord)):
        print("\nCongratulations! Your password is valid!")
   
# --- Execute ----------

main()

1 Comment

Thank you for your help, Javad! I was reading other suggestions on some other questions that were similar to mine and someone mentioned created a separate function to look specifically for the digit or alphabet character, so it's nice to see it in action here. Thank you again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.