Open In App

Password validation in Python

Last Updated : 18 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Creating a strong password is one of the simplest yet most important steps for keeping accounts secure. A valid password usually contains mix of uppercase and lowercase letters, at least one number, at least one special symbol, a length that’s neither too short nor too long etc.

In this article, we will explore three different methods to check whether a given password meets these rules.

Validation Rules

For this example, a valid password must:

  1. Have at least one number
  2. Have at least one uppercase letter
  3. Have at least one lowercase letter
  4. Have at least one special character ($, @, #, %)
  5. Be between 6 and 20 characters in length

Example Inputs and Outputs

Input: Geek12#
Output: Password is valid.

Input: asd123
Output: Invalid Password.

Let's explore different methods to do this:

1. Using Regex (Regular Expressions)

We can use a single regular expression to check all password rules at once like length, uppercase, lowercase, digits and special symbols making the validation compact and efficient.

Python
import re
def main():
    passwd = 'Geek12@'

    # Regex pattern for password validation
    reg = r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$#%])[A-Za-z\d@$#%]{6,20}$"

    # Compile regex
    pat = re.compile(reg)

    # Search pattern in password
    mat = re.search(pat, passwd)

    if mat:
        print("Password is valid.")
    else:
        print("Password invalid !!")

if __name__ == '__main__':
    main()

Output
Password is valid.

Explanation:

  • reg = r"pattern" Check every validation condition
  • re.compile(reg): Compiles the regex for reuse.
  • re.search(pat, passwd): Checks if the password matches the pattern.
  • If match found prints "Password is valid." else prints "Password invalid !!"

2. Using ASCII Values & Single Loop

This approach checks all password rules in a single loop by using ord() to get each character’s ASCII value. It efficiently identifies digits, uppercase letters, lowercase letters and special symbols without multiple any() calls.

Python
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 not be greater than 20')
        val = False

    # Flags for each condition
    has_digit = has_upper = has_lower = has_sym = False

    for char in passwd:
        if 48 <= ord(char) <= 57:
            has_digit = True
        elif 65 <= ord(char) <= 90:
            has_upper = True
        elif 97 <= 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

# Test cases
print(password_check('Geek12@'))          
print(password_check('helloWORLD123@'))   
print(password_check('HelloWORLD123'))    

Output
True
True
Password should have at least one of the symbols $@#%
False

Explanation:

  • SpecialSym: List of allowed special symbols.
  • Checks password length (must be between 6 and 20).
  • Initializes flags (has_digit, has_upper, has_lower, has_sym) to track conditions.
  • Loops through each character, use ord() to check if it’s a digit, uppercase, lowercase or special symbol.
  • After the loop, prints errors if any condition is missing.
  • Returns True if all rules pass, else False.

3. Naive Method

This method uses simple built-in string functions like .isdigit(), .isupper() and .islower() to manually check each password rule. It’s straightforward to understand but requires multiple separate checks for each condition.

Python
def password_check(passwd):
    SpecialSym = ['$', '@', '#', '%']
    val = True

    # Check length
    if len(passwd) < 6:
        print('Length should be at least 6')
        val = False
        
    if len(passwd) > 20:
        print('Length should not be greater than 20')
        val = False

    # Check for digits
    if not any(char.isdigit() for char in passwd):
        print('Password should have at least one numeral')
        val = False

    # Check for uppercase letters
    if not any(char.isupper() for char in passwd):
        print('Password should have at least one uppercase letter')
        val = False

    # Check for lowercase letters
    if not any(char.islower() for char in passwd):
        print('Password should have at least one lowercase letter')
        val = False

    # Check for special symbols
    if not any(char in SpecialSym for char in passwd):
        print('Password should have at least one of the symbols $@#%')
        val = False

    return val

# Main function
def main():
    passwd = 'Geek12@'
    if password_check(passwd):
        print("Password is valid")
    else:
        print("Invalid Password !!")

if __name__ == '__main__':
    main()

Output
Password is valid

Explanation:

  • password_check(passwd): Validates a password based on multiple rules. Returns True if all checks pass, else False.
  • main(): Tests password "Geek12@" and prints whether it’s valid or not.

Related Articles:


Password validation in Python
Article Tags :
Practice Tags :

Explore