Python Random Password Generator Program

Short answer
A Python password generator joins randomly chosen characters from string.ascii_letters, string.digits and string.punctuation. For real passwords use the secrets module instead of random, because random is predictable.

Password generators are a good exercise in strings, loops and the random module. You build a pool of allowed characters, pick characters from it at random and join them into one string.

There is one important warning. The random module is designed for games and simulations and is not secure: its output can be predicted. The examples here use random.seed() only so the output on this page is repeatable. A password you will actually use must be generated with secrets, shown in the last section.

Quick facts
InputThe desired password length (and optionally which character types to include)
OutputA random password string
ApproachBuild a pool of characters, choose length characters, join them
Time complexityO(length)

Approach: how to generate a random password step by step

  1. Import random and string.
  2. Build the pool: string.ascii_letters + string.digits + string.punctuation.
  3. Pick one character at a time with random.choice(pool) length times.
  4. Combine them with "".join(...) (see str.join()).
  5. To guarantee the password contains each type, choose one character from each group first, fill the rest from the full pool, then shuffle.

How the password generator code works

string.ascii_letters is abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ, string.digits is 0123456789 and string.punctuation holds symbols such as !@#$%. A generator expression produces the characters and join() turns them into one string. random.shuffle() mixes a list in place, which is why the guaranteed characters do not always sit at the start.

Python
import string

print(string.digits)
print(string.ascii_lowercase)
print(len(string.punctuation))

Variations: secure passwords with the secrets module

For anything real, replace random.choice with secrets.choice. The secrets module draws from the operating system's secure random source and cannot be seeded, so its output is different on every run (which also means it cannot be used with fixed expected output):

import secrets
import string

pool = string.ascii_letters + string.digits + string.punctuation
password = "".join(secrets.choice(pool) for _ in range(16))
print(password)

random vs secrets for passwords

Aspect`random``secrets`
PurposeGames, simulations, samplingPasswords, tokens, security
Predictable with a seed?YesNo (cannot be seeded)
Same output every run with seed()?YesNever
Choose one itemrandom.choice(seq)secrets.choice(seq)
Safe for real passwords?NoYes

Examples you can run

Press Run, then edit the code and run it again.

Basic 12-character password

Seed 10 makes the demo output repeatable; a real program would not call seed.

Basic 12-character password
import random
import string

random.seed(10)
pool = string.ascii_letters + string.digits
password = "".join(random.choice(pool) for _ in range(12))
print(password)
print(len(password))
Expected outputKcBEKanD0F0r
12

Password with at least one of each character type

The function picks one letter, one digit and one symbol first, then fills the rest and shuffles so the order is not predictable.

Password with at least one of each character type
import random
import string

def generate_password(length=12):
    chars = [
        random.choice(string.ascii_lowercase),
        random.choice(string.ascii_uppercase),
        random.choice(string.digits),
        random.choice(string.punctuation),
    ]
    pool = string.ascii_letters + string.digits + string.punctuation
    while len(chars) < length:
        chars.append(random.choice(pool))
    random.shuffle(chars)
    return "".join(chars)

random.seed(5)
pwd = generate_password(10)
print(pwd)
print(any(c.isdigit() for c in pwd), any(c.isupper() for c in pwd))
Expected output@5oIt7u"gF
True True

Edge case: length too short

If the requested length is smaller than the number of required character types, the function should refuse instead of returning an unsafe password.

Edge case: length too short
import random
import string

def generate_password(length):
    if length < 4:
        raise ValueError("length must be at least 4")
    pool = string.ascii_letters + string.digits
    return "".join(random.choice(pool) for _ in range(length))

try:
    generate_password(2)
except ValueError as error:
    print("Error:", error)
Expected outputError: length must be at least 4

Ask the user for the length

The length is typed by the user and converted with int(). Seed 1 keeps the demo repeatable.

Ask the user for the length
import random
import string

random.seed(1)
length = int(input("Password length: "))
pool = string.ascii_letters + string.digits + "!@#$%"
print("".join(random.choice(pool) for _ in range(length)))
Expected outputPassword length: 8
riGp@58W

Common mistakes

Using random for real passwords

✗ Wrong

import random
import string

pool = string.ascii_letters + string.digits
password = "".join(random.choice(pool) for _ in range(12))
No error, but the Mersenne Twister generator behind `random` is predictable and is not suitable for security.

✓ Right

import secrets
import string

pool = string.ascii_letters + string.digits
password = "".join(secrets.choice(pool) for _ in range(12))
print(len(password))

Use secrets.choice(pool) in the same expression for passwords and tokens.

Calling random.choice on a number

✗ Wrong

import random

random.choice(12345)
TypeError: object of type 'int' has no len()

✓ Right

import random
import string

print(len(random.choice(string.digits)))

choice() needs a sequence such as a string or list. Use string.digits for digits.

Python Random Password Generator Program: questions people ask

How do I generate a random password in Python?

Build a pool of characters with the string module and join secrets.choice(pool) repeated length times. Use secrets, not random, for real passwords.

Is random.choice safe for generating passwords?

No. The random module is predictable and meant for simulations; the secrets module is designed for passwords, tokens and other security-sensitive values.

How long should a generated password be?

At least 12 characters is a common minimum, and longer is better. Mixing letters, digits and symbols from a 94-character pool adds about 6.5 bits of strength per character.

Keep learning

Step-by-step lessons:
Python random ModulePython StringsPython for Loops

Related:
Python Number Guessing Game ProgramPython String join() MethodPython Rock Paper Scissors Game ProgramPython random Module

More in mini programs:
Python Number Guessing Game ProgramPython Simple Calculator ProgramPython BMI Calculator ProgramPython Rock Paper Scissors Game ProgramPython Tip Calculator Program (Split the Bill)Python Star Pattern Programs (Triangle, Pyramid, Diamond) See all →