VOOZH about

URL: https://www.geeksforgeeks.org/python/password-validation-in-python/

⇱ Password validation in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Password validation in Python

Last Updated : 18 Aug, 2025

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.


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.


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.


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:

Comment
Article Tags: