Python Program to Generate a Random Password
Beginner · Strings
A strong password mixes lowercase letters, uppercase letters, digits and symbols, and is long enough to be hard to guess. This program builds a random password of a chosen length that always contains at least one character of each kind, using the random and string modules.
Program
Your random password: nREA7+NQ3vO< Length: 12
How it works
string.ascii_lowercase,string.ascii_uppercase,string.digitsandstring.punctuationare ready-made strings holding every lowercase letter, uppercase letter, digit and symbol.- Picking one character from each group first guarantees that the password passes the usual "must contain" rules.
- The
whileloop adds random characters from all the groups until the password reacheslength. random.shuffle()mixes the list, and"".join(password)turns the list of characters into one string.- The password is different on every run. For real accounts, use the
secretsmodule shown below, which is made for security.
Another way to write it
Using the secrets module (for real passwords)
Secure password: Kuyyw8Bu#WFRdbbP
The random module is fine for games, but its numbers can be predicted by someone who sees enough of them. secrets uses the operating system's secure random source, so use it for anything real. Leaving out symbols that are hard to type, like quotes and backslashes, also makes the password easier to enter.
Try it yourself
Change the program so it leaves out characters that look alike, such as O and 0 or l and 1.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Simulate a Dice Roll
- Count the Frequency of Each Character in a String
- Store and Search User IDs and Passwords in a CSV File
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Check a Palindrome String
- Reverse a String
- Count the Words in a String
- Remove Punctuation from a String
- Sort Words in Alphabetical Order
All Python programs · CBSE class 12 practical file · Python exercises