This is a very simple password verification code. But it is very effective.

Step 1: First we take a user input. That is a test password.
Step 2: Call a function to verify the password
Step 3: Verify the returns of the function

Step 1:

passwd = raw_input(“Enter a Test Password:”)
raw_input takes a string type user input.

step 2:

Let’s call a function named passwordverify and it takes a parameter pw1.

def passwordverify(pw1):

We need the length of the password, because we need to loop through each character.

pw_len = len(pw1)

Then, we define 04 variables. Each represents a type of character we use in the password.

char_uc = 0   #for uppercase characters
char_lc = 0   #for lowercase characters
char_nm = 0   #for numeric characters
char_sp = 0   #for special characters

Next, we take all the possible characters under above categories. They are seperated by white spaces.
The function ‘split()’ will break the character set into a list of groups at each white space.

charsets = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 1234567890 !@$%^&*()_-+={}[]|\,.></?~`\:;’.split()

Now let’s check availability of each character in our test password with compared to above character groups.

for i in range(pw_len):

if pw1[i] in charsets[0]:
char_uc = 1
if pw1[i] in charsets[1]:
char_lc = 1
if pw1[i] in charsets[2]:
char_nm = 1
if pw1[i] in charsets[3]:
char_sp = 1

If a character in test password is matched with any of the character in character group, the four variables (char_uc, char_lc, char_nm and char_sp) are manipulated.
I have used number 1 to manipulate the four variables (char_uc, char_lc, char_nm and char_sp).

If all type of characters are found in the test password then char_uc + char_lc + char_nm + char_sp should be 4.

if ((char_uc + char_lc + char_nm + char_sp) > 3):
return 5 #return anything you want; Just to say OK

Then, if the char_uc + char_lc + char_nm + char_sp is not 4, that means there is a lack of a character type.
In that case, we can return an appropreate value to identify which group of characters are missing from your test password.

elif ((char_uc + char_lc + char_nm + char_sp) < 4):
if (char_uc == 0):
return 0
if (char_lc == 0):
return 1
if (char_nm == 0):
return 2
if (char_sp == 0):
return 3

Step 3:

In this step you can use what the function returns to notify the user what type of characters are missing in the test
password.(Or everything is fine)

if (pw_verify!=5): #If not equal what the function returns when everything is OK
if(pw_verify==0):
print “No Upper Case Characters”
if(pw_verify==1):
print “No Lower Case Characters”
if(pw_verify==2):
print “No Numeric Characters”
if(pw_verify==3):
print “No Special Characters”
else:
print “Password OK”

That’s all. You can download the code here. (You better code it yourself.)

Password Verification in Python 2

Leave a Reply

Your email address will not be published. Required fields are marked *