Python program to check the validity of a Password

In this program, we will be taking a password as a combination of alphanumeric characters along with special characters, and check whether the password is valid or not with the help of few conditions.

Primary conditions for password validation :

  1. Minimum 8 characters.
  2. The alphabets must be between [a-z]
  3. At least one alphabet should be of Upper Case [A-Z]
  4. At least 1 number or digit between [0-9].
  5. At least 1 character from [ _ or @ or $ ].


Input : R@m@_f0rtu9e$
Output : Valid Password

Input : Rama_fortune$
Output : Invalid Password
Explanation: Number is missing

Input : Rama#fortu9e 
Output : Invalid Password
Explanation: Must consist from _ or @ or $

Here we have used the re module that provide support for regular expressions in Python. Along with this the method returns False (if the first parameter is not found in the second parameter) This method is best suited for testing a regular expression more than extracting data. We have used the to check the validation of alphabets, digits or special characters. To check for white spaces we use the “\s” which comes in the module of the regular expression.





# Python program to check validation of password
# Module of regular expression is used with search()
import re
password = "R@m@_f0rtu9e$"
flag = 0
while True:  
    if (len(password)<8):
        flag = -1
    elif not"[a-z]", password):
        flag = -1
    elif not"[A-Z]", password):
        flag = -1
    elif not"[0-9]", password):
        flag = -1
    elif not"[_@$]", password):
        flag = -1
    elif"\s", password):
        flag = -1
        flag = 0
        print("Valid Password")
if flag ==-1:
    print("Not a Valid Password")



Valid Password

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.