It is very important to secure our online accounts with a strong password. A weak password can make our accounts more vulnerable and easier to access. In this article, we will learn how to create a simple Python program to check the strength of a password.
We will use the re module in Python, which allows us to work with regular expressions. Regular expressions help us match patterns in a string, a good choice for validating passwords.
Let’s get started!
Important Points to Remember
Passwords must be at least 10 characters long and must include:
- At least one lowercase letter (a-z)
- At least one uppercase letter (A-Z)
- At least one number (0-9)
- At least one special character (@#$%^&+=!)
Remember, a strong password is harder to guess or crack.
Python Code to Check Password Strength
Here is the complete code to check if a password is strong:
import re check_pass = re.compile(r'''( ^.*(?=.{10,}) # Checking the length, minimum 10 characters (?=.*\d) # At least one Numeric Digit (?=.*[a-z]) # At least one Lowercase letter (a to z) (?=.*[A-Z]) # At least one Uppercase letter (A to Z) (?=.*[@#$%^&+=!]).*$ # At least one Special Character )''', re.VERBOSE) passCode = input('Enter the Password: ') mo1 = check_pass.search(passCode) # Check if the password is valid or not if mo1: print("Strong Password.") else: print("Not Valid! Weak Password.")
Output
Enter the Password: GoogleGoogleHappyBirthday@23 Strong Password.
Enter the Password: password123 Not Valid! Weak Password.
Line-by-Line Explanation of the Code
Let’s understand how the program works, especially the regular expression (regex) part:
Import the re module
import re
re
is Python’s built-in library for working with regular expressions.
Compile the password checking pattern
check_pass = re.compile(r'''(...)''', re.VERBOSE)
Here:
- We create a regular expression pattern inside
re.compile
. re.VERBOSE
allows us to write the regex in a readable, multi-line format with comments.
Inside the Regular Expression:
^.*(?=.{10,})
^
means the start of the string..*
means any character (0 or more times).(?=.{10,})
ensures that the password has at least 10 characters
(?=.*\d)
\d
matches any digit (0-9).- This checks that the password has at least one number.
(?=.*[a-z])
- Matches at least one lowercase letter (from a to z).
(?=.*[A-Z])
- Matches at least one uppercase letter (from A to Z).
(?=.*[@#$%^&+=!])
- Checks for at least one special character like
@, #, $, %, ^, &, +, =, !
.
.*$
.*
means any character.$
marks the end of the string.