The Wayback Machine - https://web.archive.org/web/20240930191433/https://www.geeksforgeeks.org/python-program-check-validity-password/
Open In App

Python program to check the validity of a Password

Last Updated : 06 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 

Python
# 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: 

Python
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

Python
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
Generating Strong Password using Python
Having a weak password is not good for a system that demands high confidentiality and security of user credentials. It turns out that people find it difficult to make up a strong password that is strong enough to prevent unauthorized users from memorizing it. This article uses a mixture of numbers, alphabets, and other symbols found on the computer
3 min read
How to Build a Password Manager in Python
We have a task to create a Password Manager in Python. In this article, we will see how to create a Password Manager in Python. What is a Password Manager?A Password Manager in Python is a tool in which we can add the username and password. Additionally, it allows us to retrieve the username and password. We also have the option to view all added u
7 min read
EasyGUI – Password Box
Password Box : It is used to get the input from the user which is in form of password i.e masked input, input can be any keyboard input, it takes input in form of string. It displays the title, message to be displayed, place to enter a text and a pair of "Ok", "Cancel" button which is used confirm the input. Also we can set some default text to the
2 min read
EasyGUI – Multi Password Box
Multi Password Box : It is used to get the input from the user which is in form of multiple text and single password i.e masked input, input can be any keyboard input, it takes input in form of string. It displays the title, message to be displayed, group of places to enter a text and a pair of "Ok", "Cancel" button which is used confirm the input.
3 min read
How to change password of superuser in Django?
Django provides us Admin Panel for it’s users to look over the database and other activities. If you dont know how to create superuser then you can refer to How to create superuser in Django? How to change password of superuser in Django? For changing password of superuser, first reach the same directory as that of manage.py and run the following c
1 min read
How to store username and password in Flask
We'll discuss how to save a Username and password on a Flask website in this article. We may view the welcome message and the username we chose when registering on the profile page after logging in with our username and password. The names of subsequent users who sign up using the login information we'll be using here will also show up on the profi
9 min read
Password Hashing with Bcrypt in Flask
In this article, we will use Password Hashing with Bcrypt in Flask using Python. Password hashing is the process of converting a plaintext password into a hashed or encrypted format that cannot be easily reverse-engineered to reveal the original password. Bcrypt is a popular hashing algorithm used to hash passwords. It is a password-hashing functio
2 min read
What is the Minimum Length of Password in Django?
In Django, the default minimum period for passwords is 8 characters. This method that while you create a personal account or alternate a password, Django enforces a minimal password period of eight characters by default. However, you could customize this minimum length by enhancing your mission's settings. In Django, you could set the minimum durat
3 min read
How to Generate a Random Password Using Ruby?
Generating a random password is a fundamental task in cybersecurity and application development. Creating a secure random password is very easy with the Ruby library. This article will show how to generate a random password in Ruby in Python. Generate a Random Password Using RubyBelow are the code examples of how to Generate a Random Password using
2 min read
How to Reset Django Admin Password?
Forgetting or needing to reset the admin password in Django is a common issue that can be resolved in a few easy steps. Django provides several ways to reset the admin password, depending on the situation. In this article, we'll explore multiple methods to help you recover or reset the password for your Django admin account. Reset Password via Djan
2 min read
Python program to check if the list contains three consecutive common numbers in Python
Our task is to print the element which occurs 3 consecutive times in a Python list. Example : Input : [4, 5, 5, 5, 3, 8] Output : 5 Input : [1, 1, 1, 64, 23, 64, 22, 22, 22] Output : 1, 22 Approach : Create a list.Create a loop for range size – 2.Check if the element is equal to the next element.Again check if the next element is equal to the next
3 min read
Python Program for How to check if a given number is Fibonacci number?
Given a number \'n\', how to check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .. Examples : Input: 8Output: Yes Input: 34Output: Yes Input: 41Output: No Following is an interesting property about Fibonacci numbers that can also be used to check if a given number is Fibonacci or not. A n
2 min read
Python List Equality | Program to check if two given matrices are identical
We are given two square matrices of same order. Check if two given matrices are identical. Examples: Input : A = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] B = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] Output: Matrices are identical We have existing solution for this problem please refer C Program to check if two give
3 min read
Python Program for Check if all digits of a number divide it
Given a number n, find whether all digits of n divide it or not. Examples: Input : 128Output : Yes128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. Input : 130Output : No We want to test whether each digit is non-zero and divides the number. For example, with 128, we want to test d != 0 && 128 % d == 0 for d = 1, 2, 8. To do that, we need to it
3 min read
Python Program to check whether it is possible to make a divisible by 3 number using all digits in an array
Given an array of integers, the task is to find whether it's possible to construct an integer using all the digits of these numbers such that it would be divisible by 3. If it is possible then print "Yes" and if not print "No". Examples: Input : arr[] = {40, 50, 90} Output : Yes We can construct a number which is divisible by 3, for example 945000.
2 min read
Python Program to Check Armstrong Number
Given a number x, determine whether the given number is Armstrong number or not. A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if. abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + .... Example: Input : 153 Output : Yes 153 is an Armstrong number. 1*1*1 + 5*5*5 + 3*3*3 = 153 Input : 120 Outp
6 min read
Python Program to Check if String is Empty or Not
Python strings are immutable and have more complex handling when discussing their operations. Note that a string with spaces is actually an empty string but has a non-zero size. This article also discussed that problem and the solution to it. Let's see different methods of Check if String is Empty Python. Example Input:[" "]Output: YesExplanation:
8 min read
Python program to check if given string is vowel Palindrome
Given a string (may contain both vowel and consonant letters), remove all consonants, then check if the resulting string is palindrome or not. Examples: Input : abcuhuvmnba Output : YES Explanation : The consonants in the string "abcuhuvmnba" are removed. Now the string becomes "auua". Input : xayzuezyax Output : NO Input : bkldhgcj Output : -1 App
5 min read
Python program to check if given string is pangram
Given a string, write a Python program to check if that string is Pangram or not. A pangram is a sentence containing every letter in the English Alphabet. Examples: Input : The quick brown fox jumps over the lazy dog Output : Yes Input : abcdefgxyz Output : No We have already discussed the naive approach of pangram checking in this article. Now, le
5 min read
Python program to check if a given string is Keyword or not
Given a string, write a Python program that checks if the given string is keyword or not. Keywords are reserved words which cannot be used as variable names.There are 33 keywords in Python programming language.(in python 3.6.2 version) Examples: Input: str = "geeks" Output: geeks is not a keyword Input: str = "for" Output: for is a keyword We can a
3 min read