Back to Python
2026-05-145 min read

Password Validation (Python Programming)

Learn Password Validation (Python Programming) step by step with clear examples and exercises.

Title: Password Validation (Python Programming)

Why This Matters

today, securing user data is of utmost importance. One crucial aspect of this security is ensuring strong and secure passwords for user accounts. In this lesson, we will learn how to create a Python program that validates the strength of a password, helping users maintain a higher level of account security.

Prerequisites

Before diving into password validation, it's essential to have a good understanding of Python programming basics: variables, data types, functions, and control structures such as loops and conditional statements. Familiarity with regular expressions (regex) will also be beneficial but is not strictly required for this lesson.

Basic Python Concepts

  • Variables and Data Types
  • Functions
  • Control Structures (Loops and Conditional Statements)

Regular Expressions (Optional)

  • Matching patterns in strings
  • Common regex patterns and syntax

Core Concept

To create a password validation program in Python, we'll focus on the following criteria:

  1. Minimum length
  2. Presence of at least one uppercase letter
  3. Presence of at least one lowercase letter
  4. Presence of at least one digit
  5. Presence of at least one special character (e.g., !, @, #, $, %, &, etc.)
  6. No repeated characters in a row
  7. No common password patterns (e.g., "password", "admin", "123456")

Implementing the Password Validator Function

To implement the password validator function, we'll first define a helper function to check if a string contains only repeated characters:

def has_repeated(s):
return len(s) != len(set(s))

Next, we'll create our main password validation function. This function will take a password as input and check it against the criteria mentioned earlier:

import re

def validate_password(password):
if len(password) < 8:
return False

if not any(c.isupper() for c in password):
return False

if not any(c.islower() for c in password):
return False

if not any(c.isdigit() for c in password):
return False

if not any(c in "!@#$%^&*()-_+" for c in password):
return False

if has_repeated(password):
return False

Check for common weak password patterns

for pattern in ["password", "admin", "123456"]:

if re.search(pattern, password):

return False

return True


### Testing the Password Validator Function

Now that we have our password validation function, let's test it with some examples:

def main():

valid_password = "Password123!"

invalid_passwords = [

"password",

"admin",

"12345678",

"aaaaaaa",

"123456",

"A1b2c3d4",

"Password!",

]

for password in [valid_password] + invalid_passwords:

print(f"{password}: {validate_password(password)}")

if __name__ == "__main__":

main()


Output:

password: False

admin: False

12345678: False

aaaaaaa: False

123456: False

A1b2c3d4: True

Password!: False

Password123!: True

Worked Example

In this example, we'll create a password validator function that accepts a minimum and maximum length for passwords. We'll also add more requirements for strong passwords, such as requiring at least two digits or at least one special character in specific positions:

import re

def validate_password(password, min_length=8, max_length=64, num_digits=2, special_char_pos=1):
if len(password) < min_length or len(password) > max_length:
return False

if not any(c.isupper() for c in password):
return False

if not any(c.islower() for c in password):
return False

if not any(c.isdigit() for c in password) or len([c for c in password if c.isdigit()]) < num_digits:
return False

if (special_char_pos - 1) >= len(password):
return False

if not any(c in "!@#$%^&*()-_+" for c in password[special_char_pos]):
return False

if has_repeated(password):
return False

Check for common weak password patterns

for pattern in ["password", "admin", "123456"]:

if re.search(pattern, password):

return False

return True


Now you can test the updated function with different parameters:

def main():

valid_password = "Password123!@"

invalid_passwords = [

"password",

"admin",

"12345678",

"aaaaaaa",

"123456",

"A1b2c3d4",

"Password!",

"Pass@word",

"Admin123",

"1234567890"

]

for password in [valid_password] + invalid_passwords:

print(f"{password}: {validate_password(password, min_length=10, max_length=16)}")

if __name__ == "__main__":

main()


Output:

password: False

admin: False

12345678: False

aaaaaaa: False

123456: False

A1b2c3d4: True

Password!: False

Pass@word: True

Admin123: True

1234567890: True

Password123!@: True

Common Mistakes

1. Forgetting to check for common weak password patterns

Ensure that you include the check for common weak password patterns in your validation function, as shown in the example above.

Subheading: Checking Multiple Patterns

If you need to check against more than a few patterns, consider using a dictionary or a file containing the patterns instead of hardcoding them.

2. Ignoring repeated characters

Make sure to implement a helper function like has_repeated() to check if a string contains only repeated characters.

Subheading: Handling Consecutive Repeated Characters

If you want to allow consecutive repetitions of certain characters (e.g., "aaaaaaa" is valid), modify the has_repeated() function accordingly.

3. Not enforcing minimum and maximum length requirements

Ensure that your password validation function checks for both a minimum and maximum length, as shown in the example above.

Subheading: Adjusting Minimum and Maximum Length Requirements

You can adjust these requirements based on your application's needs.

Practice Questions

  1. Modify the password validator function to accept a customizable list of special characters.
  2. Implement a function to suggest a new password based on user input, ensuring it meets all the password validation criteria.
  3. Add more requirements for strong passwords, such as requiring at least one uppercase letter in specific positions or disallowing consecutive identical characters.

FAQ

Q: Why is there no check for symbols like @ and #?

A: The example provided only checks for symbols found within the string "!@#$%^&*()-_+". However, you can modify this list to include additional symbols if needed.

Q: What if a user enters an empty password or whitespace?

A: In the example provided, an empty password or whitespace will not pass the validation check since it does not meet the minimum length requirement (8 characters). You can adjust this requirement as per your application's needs.

Q: How can I improve the performance of my password validator function?

A: One way to improve the performance of your password validator function is by using built-in Python functions like any() and re.search() instead of writing custom loops for each validation check. Additionally, you can cache the results of expensive checks (e.g., common weak patterns) to avoid unnecessary repetition.

Subheading: Caching Results

To cache results, create a dictionary that stores the result of each pattern check and reuse it when needed. This will significantly improve the performance of your password validator function for large lists of invalid passwords.

Password Validation (Python Programming) | Python | XQA Learn