Python Program for Password with Certain Requirements

Question:

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()
Asked By: Jessica G.

||

Answers:

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

Answered By: Ali Davood

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:
Answered By: j1-lee

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()
Answered By: Javad Nikbakht
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.