Editor

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

password_generator.py
import random
import string
length = 12 # or: length = int(input("Password length: "))
# One character of each kind, so the password always has a mix
password = [
random.choice(string.ascii_lowercase),
random.choice(string.ascii_uppercase),
random.choice(string.digits),
random.choice(string.punctuation),
]
# Fill the rest with characters of any kind
all_characters = string.ascii_letters + string.digits + string.punctuation
while len(password) < length:
password.append(random.choice(all_characters))
random.shuffle(password) # mix them, so the first four are not in a fixed order
print("Your random password:", "".join(password))
print("Length:", len(password))
Output
Your random password: nREA7+NQ3vO<
Length: 12

How it works

  1. string.ascii_lowercase, string.ascii_uppercase, string.digits and string.punctuation are ready-made strings holding every lowercase letter, uppercase letter, digit and symbol.
  2. Picking one character from each group first guarantees that the password passes the usual "must contain" rules.
  3. The while loop adds random characters from all the groups until the password reaches length.
  4. random.shuffle() mixes the list, and "".join(password) turns the list of characters into one string.
  5. The password is different on every run. For real accounts, use the secrets module shown below, which is made for security.

Another way to write it

Using the secrets module (for real passwords)

Using the secrets module (for real passwords)
import secrets
import string
characters = string.ascii_letters + string.digits + "!@#%&*?"
password = ""
for i in range(16):
password += secrets.choice(characters)
print("Secure password:", password)
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises