Password validation in Python
Last Updated :
30 Dec, 2022
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.
- Should be between 6 to 20 characters long.
Input : Geek12#
Output : Password is valid.
Input : asd123
Output : Invalid Password !!
We can check if a given string is eligible to be a password or not using multiple ways. Method #1: Naive Method (Without using Regex).
Python3
# Password validation in Python
# using naive method
# Function to validate the password
def password_check(passwd):
SpecialSym =['$', '@', '#', '%']
val = True
if len(passwd) < 6:
print('length should be at least 6')
val = False
if len(passwd) > 20:
print('length should be not be greater than 8')
val = False
if not any(char.isdigit() for char in passwd):
print('Password should have at least one numeral')
val = False
if not any(char.isupper() for char in passwd):
print('Password should have at least one uppercase letter')
val = False
if not any(char.islower() for char in passwd):
print('Password should have at least one lowercase letter')
val = False
if not any(char in SpecialSym for char in passwd):
print('Password should have at least one of the symbols $@#')
val = False
if val:
return val
# Main method
def main():
passwd = 'Geek12@'
if (password_check(passwd)):
print("Password is valid")
else:
print("Invalid Password !!")
# Driver Code
if __name__ == '__main__':
main()
This code used boolean functions to check if all the conditions were satisfied or not. We see that though the complexity of the code is basic, the length is considerable. Method #2: Using regex compile() method of Regex module makes a Regex object, making it possible to execute regex functions onto the pat variable. Then we check if the pattern defined by pat is followed by the input string passwd. If so, the search method returns true, which would allow the password to be valid.
Python3
# importing re library
import re
def main():
passwd = 'Geek12@'
reg = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!#%*?&]{6,20}$"
# compiling regex
pat = re.compile(reg)
# searching regex
mat = re.search(pat, passwd)
# validating conditions
if mat:
print("Password is valid.")
else:
print("Password invalid !!")
# Driver Code
if __name__ == '__main__':
main()
Output:Password is valid.
Using ascii values and for loop:
This code uses a function that checks if a given password satisfies certain conditions. It uses a single for loop to iterate through the characters in the password string, and checks if the password contains at least one digit, one uppercase letter, one lowercase letter, and one special symbol from a predefined list and based on ascii values. It sets a boolean variable "val" to True if all these conditions are satisfied, and returns "val" at the end of the function.
The time complexity of this code is O(n), where n is the length of the password string. The space complexity is O(1), as the size of the variables used in the function does not depend on the size of the input.
Python3
def password_check(passwd):
SpecialSym =['$', '@', '#', '%']
val = True
if len(passwd) < 6:
print('length should be at least 6')
val = False
if len(passwd) > 20:
print('length should be not be greater than 8')
val = False
# Check if password contains at least one digit, uppercase letter, lowercase letter, and special symbol
has_digit = False
has_upper = False
has_lower = False
has_sym = False
for char in passwd:
if ord(char) >= 48 and ord(char) <= 57:
has_digit = True
elif ord(char) >= 65 and ord(char) <= 90:
has_upper = True
elif ord(char) >= 97 and ord(char) <= 122:
has_lower = True
elif char in SpecialSym:
has_sym = True
if not has_digit:
print('Password should have at least one numeral')
val = False
if not has_upper:
print('Password should have at least one uppercase letter')
val = False
if not has_lower:
print('Password should have at least one lowercase letter')
val = False
if not has_sym:
print('Password should have at least one of the symbols $@#')
val = False
return val
print(password_check('Geek12@')) # should return True
print(password_check('asd123')) # should return False
print(password_check('HELLOworld')) # should return False
print(password_check('helloWORLD123@')) # should return True
print(password_check('HelloWORLD123')) # should return False
#This code is contributed by Edula Vinay Kumar Reddy
OutputTrue
Password should have at least one uppercase letter
Password should have at least one of the symbols $@#
False
Password should have at least one numeral
Password should have at least one of the symbols $@#
False
True
Password should have at least one of the symbols $@#
False
Similar Reads
Input Validation in Python String In Python, string input validation helps ensure that the data provided by the user or an external source is clean, secure and matches the required format. In this article, we'll explore how to perform input validation in Python and best practices for ensuring that strings are correctly validated.Pyt
2 min read
Getting Saved Wifi Passwords using Python Usually while connecting with the wifi we have to enter some password to access the network, but we are not directly able to see the password we have entered earlier i.e password of saved network. In this article, we will see how we can get all the saved WiFi name and passwords using Python, in orde
3 min read
Generate Random Strings for Passwords in Python A strong password should have a mix of uppercase letters, lowercase letters, numbers, and special characters. The efficient way to generate a random password is by using the random.choices() method. This method allows us to pick random characters from a list of choices, and it can repeat characters
2 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 pas
7 min read
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 checking whether the password is valid or not with the help of a few conditions.Primary conditions for password validation:Minimum 8 characters.The alphabet must be between [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 al
2 min read
Python String Input Output In Python, input and output operations are fundamental for interacting with users and displaying results. The input() function is used to gather input from the user and the print() function is used to display output.Input operations in PythonPythonâs input() function allows us to get data from the u
3 min read
Personalized Task Manager in Python In this article, we are going to create a task management software in Python. This software is going to be very useful for those who don't want to burden themselves with which task they have done and which they are left with. Being a coder we have to keep in mind which competition is going on, which
10 min read
Python - Generate Random String of given Length Generating random strings is a common requirement for tasks like creating unique identifiers, random passwords, or testing data. Python provides several efficient ways to generate random strings of a specified length. Below, weâll explore these methods, starting from the most efficient.Using random.
2 min read
List As Input in Python in Single Line Python provides several ways to take a list as input in Python in a single line. Taking user input is a common task in Python programming, and when it comes to handling lists, there are several efficient ways to accomplish this in just a single line of code. In this article, we will explore four com
3 min read