Trying to check if password contains both letters and numbers with python

544 views Asked by At

I am trying to create python code that checks whether a password is:

Is at least 6 characters long. Contains both letters and numbers. Isn't letters only. Isn't numbers only.

Doesn't use any: Imported libraries. Loop Structures. User defined inputs.

Here is the code:

MIN_PASSWORD_LENGTH = 6
MAX_PASSWORD_LENGTH = 10
password = input('Enter your Password:\n')
password_length = len(password)

#Do I need the two lines below?
#if (len(password) < 6 or len(password) > 10) :
#    print ("Password is Weak - Doesn't Meet Length Requirements") 

#below code checks input for alphabetical characters
if password.isalpha :
    print ("Password is Weak - Only Contains Letters") 

#below code checks input for numerical characters
elif password.isnumeric :
    print ("Password is Weak - Only Contains Numbers")
#cannot get it to recognise numbers inputed into password field, mistakes numbers for letters

#below code checks input for both alphabetical and numerical characters
elif password.isalnum :
    print ("Password is Strong")

I need help with this (am I missing something?), any help would be appreciated.

3

There are 3 answers

1
Arunbh Yashaswi On
import re

def is_valid_alphanumeric_password(password):
    if not re.match(r'^[a-zA-Z0-9]{6,10}$', password):
        return False

    return True

This is a basic code for the check and re or regular expression library is pre-installed it checks for all the condition and returns True or False based on it.

0
Tim Biegeleisen On

It actually sounds like your accepted password should have a length of 6 to 10 characters and should contain both numbers and letters:

def is_valid_alphanumeric_password(password):
    if not re.search(r'^(?=.*[a-z])(?=.*[0-9])[a-z0-9]{6,10}$', password, flags=re.I):
        return False

    return True

print(is_valid_alphanumeric_password("abcdef"))  # False
print(is_valid_alphanumeric_password("123456"))  # False
print(is_valid_alphanumeric_password("abc123"))  # True

The regex pattern used here says to match:

  • ^ from the start of the password
    • (?=.*[a-z]) assert that at least one letter (any case) occurs
    • (?=.*[0-9]) assert that at least one digit occurs
    • [a-z0-9]{6,10} then match 6 to 10 alphanumeric characters
  • $ end of the password
0
NickGreen95 On

Fixed the code

 password = input('Enter your Password: ')

 if password.isalpha():
    print ("Password is Weak - Only Contains Letters") 
    
 elif password.isnumeric():
    print ("Password is Weak - Only Contains Numbers")
    
 else: 
    print ("Password is Strong")

Didn't need the following code

 MIN_PASSWORD_LENGTH = 6
 MAX_PASSWORD_LENGTH = 10
 password_length = len(password)

forgot to add () after isnumeric & isalpha