Open In App

Python program to check the validity of a Password

Last Updated : 20 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

Primary conditions for password validation:

  1. Minimum 8 characters.
  2. The alphabet 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 $ ].

Examples:

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 $

Way 1: 

Here we have used the re module that provides support for regular expressions in Python. Along with this the re.search() 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 re.search() 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. 

Python3




# 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
        break
    elif not re.search("[a-z]", password):
        flag = -1
        break
    elif not re.search("[A-Z]", password):
        flag = -1
        break
    elif not re.search("[0-9]", password):
        flag = -1
        break
    elif not re.search("[_@$]" , password):
        flag = -1
        break
    elif re.search("\s" , password):
        flag = -1
        break
    else:
        flag = 0
        print("Valid Password")
        break
 
if flag == -1:
    print("Not a Valid Password ")


Output

Valid Password

Time complexity: O(n), where n is the length of the password string.
Auxiliary space: O(1), as we are using only a few variables to store intermediate results.

Way 2: 

Python3




l, u, p, d = 0, 0, 0, 0
s = "R@m@_f0rtu9e$"
if (len(s) >= 8):
    for i in s:
 
        # counting lowercase alphabets
        if (i.islower()):
            l+=1           
 
        # counting uppercase alphabets
        if (i.isupper()):
            u+=1           
 
        # counting digits
        if (i.isdigit()):
            d+=1           
 
        # counting the mentioned special characters
        if(i=='@'or i=='$' or i=='_'):
            p+=1          
if (l>=1 and u>=1 and p>=1 and d>=1 and l+p+u+d==len(s)):
    print("Valid Password")
else:
    print("Invalid Password")


Output

Valid Password

Time complexity: O(n) where n is the length of the input string s. 
Auxiliary space: O(1) as it only uses a few variables to store the count of various characters.

Way 3: Without using any built-in method

Python3




l, u, p, d = 0, 0, 0, 0
s = "R@m@_f0rtu9e$"
capitalalphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
smallalphabets="abcdefghijklmnopqrstuvwxyz"
specialchar="$@_"
digits="0123456789"
if (len(s) >= 8):
    for i in s:
 
        # counting lowercase alphabets
        if (i in smallalphabets):
            l+=1           
 
        # counting uppercase alphabets
        if (i in capitalalphabets):
            u+=1           
 
        # counting digits
        if (i in digits):
            d+=1           
 
        # counting the mentioned special characters
        if(i in specialchar):
            p+=1       
if (l>=1 and u>=1 and p>=1 and d>=1 and l+p+u+d==len(s)):
    print("Valid Password")
else:
    print("Invalid Password")


Output

Valid Password

Time complexity : O(n), where n is the length of the input string s. 
Auxiliary space : O(1), as here only few variables are used to store the intermediate results. 



Previous Article
Next Article

Similar Reads

How To Check Uuid Validity In Python?
UUID (Universally Unique Identifier) is a 128-bit label used for information in computer systems. UUIDs are widely used in various applications and systems to uniquely identify information without requiring a central authority to manage the identifiers. This article will guide you through checking the validity of a UUID in Python. What is a UUID?A
3 min read
Python Program to generate one-time password (OTP)
One-time Passwords (OTP) is a password that is valid for only one login session or transaction in a computer or a digital device. Now a days OTP’s are used in almost every service like Internet Banking, online transactions, etc. They are generally combination of 4 or 6 numeric digits or a 6-digit alphanumeric. random() function can be used to gener
2 min read
getpass() and getuser() in Python (Password without echo)
getpass() prompts the user for a password without echoing. The getpass module provides a secure way to handle the password prompts where programs interact with the users via the terminal. getpass module provides two functions :Using getpass() function to prompt user password Syntax: getpass.getpass(prompt='Password: ', stream=None) The getpass() fu
2 min read
Python | Random Password Generator using Tkinter
With growing technology, everything has relied on data, and securing this data is the main concern. Passwords are meant to keep the data safe that we upload on the Internet. An easy password can be hacked easily and all personal information can be misused. In order to prevent such things and keep the data safe, it is necessary to keep our passwords
4 min read
Password validation in Python
Let's take 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. Conditions for a valid password are: Should have at least one number.Should have at least one uppercase and one lowercase character.Should have at least one special symbol.S
4 min read
Python | Prompt for Password at Runtime and Termination with Error Message
Say our Script requires a password, but since the script is meant for interactive use, it is likely to prompt the user for a password rather than hardcode it into the script. Python’s getpass module precisely does what it is needed. It will allow the user to very easily prompt for a password without having the keyed-in password displayed on the use
3 min read
Categorize Password as Strong or Weak using Regex in Python
Given a password, we have to categorize it as a strong or weak one. There are some checks that need to be met to be a strong password. For a weak password, we need to return the reason for it to be weak. Conditions to be fulfilled are: Minimum 9 characters and maximum 20 characters.Cannot be a newline or a spaceThere should not be three or more rep
2 min read
Create Password Protected Zip of a file using Python
ZIP is an archive file format that supports lossless data compression. By lossless compression, we mean that the compression algorithm allows the original data to be perfectly reconstructed from the compressed data. So, a ZIP file is a single file containing one or more compressed files, offering an ideal way to make large files smaller and keep re
2 min read
Create a Random Password Generator using Python
In this article, we will see how to create a random password generator using Python. Passwords are a means by which a user proves that they are authorized to use a device. It is important that passwords must be long and complex. It should contain at least more than ten characters with a combination of characters such as percent (%), commas(,), and
5 min read
Resetting Password Using Python
In this discussion, we explore creating a robust Python password reset tool using the regex library. We define a specific pattern for the password format, enhancing security. The tool incorporates parameters ensuring passwords meet criteria like uppercase/lowercase letters, digits, and special characters. It strategically uses Python libraries, suc
3 min read
three90RightbarBannerImg