Python Password Generator Example

This example shows how to build a simple password generator in Python.

You will learn how to:

  • generate a random password
  • use built-in Python modules
  • combine letters, numbers, and symbols
  • print one password to the screen

If you want a quick working version first, use this script:

import random
import string

length = 12
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))

print(password)

This creates a random 12-character password using:

  • uppercase and lowercase letters
  • numbers
  • symbols

What this example does

This script:

  • generates a random password
  • uses built-in Python modules
  • combines letters, digits, and symbols
  • prints one password to the screen

It is a good beginner project because it uses a few important Python ideas in one small program:

  • importing modules
  • working with strings
  • using a loop
  • joining values into one final result

How the script works

The script follows these steps:

  1. Import random to pick random characters.
  2. Import string to get ready-made character groups.
  3. Set a password length.
  4. Build one string of allowed characters.
  5. Pick random characters in a loop.
  6. Join the characters into one final password.

Here is the same code again:

import random
import string

length = 12
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))

print(password)

Main code example walkthrough

string.ascii_letters

string.ascii_letters gives you all lowercase and uppercase English letters.

Example:

import string

print(string.ascii_letters)

Possible output:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

string.digits

string.digits gives you the characters 0 to 9.

import string

print(string.digits)

Output:

0123456789

string.punctuation

string.punctuation gives you common symbol characters.

import string

print(string.punctuation)

Possible output:

!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

Building the characters string

This line puts all allowed characters into one string:

characters = string.ascii_letters + string.digits + string.punctuation

Now characters contains letters, numbers, and symbols.

random.choice()

random.choice() picks one random item from a sequence.

In this example, it picks one random character from characters.

import random

print(random.choice("abc123"))

Possible output:

2

If you want a beginner-friendly overview, see the Python random module overview.

''.join(...)

The generator expression creates characters one at a time.
''.join(...) combines them into one final string.

letters = ['a', 'B', '7', '!']
password = ''.join(letters)

print(password)

Output:

aB7!

Full example again

import random
import string

length = 12
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))

print(password)

Sample output:

gT8@q!2Lp#9Z

Your output will be different each time because the characters are random.


Example with user input

You can also ask the user how long the password should be.

import random
import string

length = int(input("Enter password length: "))
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))

print("Generated password:", password)

How this version works

  • input() gets text from the user
  • int() converts that text to a whole number
  • range(length) uses that number to control how many characters are chosen

If you are new to this, these pages may help:

Example run

Enter password length: 8
Generated password: A7@k9!Qp

Important note

Invalid input can cause errors.

For example, this will fail:

length = int(input("Enter password length: "))

if the user types:

abc

That causes a ValueError. If you hit that problem, see how to fix ValueError: invalid literal for int() with base 10.


How to make the password generator better

Here are a few useful ways to improve the script.

Let the user choose whether to include symbols

You can ask the user if symbols should be included.

import random
import string

length = int(input("Enter password length: "))
use_symbols = input("Include symbols? (yes/no): ").lower()

characters = string.ascii_letters + string.digits

if use_symbols == "yes":
    characters += string.punctuation

password = ''.join(random.choice(characters) for _ in range(length))

print("Generated password:", password)

Make sure the password has at least one number

A simple random password might not include a digit by chance.

This version guarantees at least one number:

import random
import string

length = 12

letters = string.ascii_letters
digits = string.digits
symbols = string.punctuation

password_chars = [
    random.choice(digits)
]

all_characters = letters + digits + symbols

for _ in range(length - 1):
    password_chars.append(random.choice(all_characters))

random.shuffle(password_chars)
password = ''.join(password_chars)

print(password)

Make sure the password has at least one symbol

You can do the same for symbols:

import random
import string

length = 12

letters = string.ascii_letters
digits = string.digits
symbols = string.punctuation

password_chars = [
    random.choice(digits),
    random.choice(symbols)
]

all_characters = letters + digits + symbols

for _ in range(length - 2):
    password_chars.append(random.choice(all_characters))

random.shuffle(password_chars)
password = ''.join(password_chars)

print(password)

Generate multiple passwords

You can print several passwords in one run:

import random
import string

length = 10
count = 5
characters = string.ascii_letters + string.digits + string.punctuation

for _ in range(count):
    password = ''.join(random.choice(characters) for _ in range(length))
    print(password)

If you want a larger example like this, see the Python random password list generator example.

Save passwords to a file only if needed

You can save generated passwords to a file, but be careful.

If a file contains real passwords, anyone who can open that file may be able to read them.

For learning, it is usually better to print them to the screen first.


Security note for beginners

The random module is fine for learning examples like this one.

For real password generation, use the secrets module instead. It is designed for security-related tasks.

That means:

  • use random to learn the idea
  • use secrets for real applications

You do not need to turn this into a full security project right away. First, make sure you understand how the basic version works.


Common problems

Here are some common mistakes beginners run into.

Forgetting to import random or string

This causes a NameError because Python does not know what random or string means.

Wrong:

length = 12
characters = string.ascii_letters + string.digits
password = ''.join(random.choice(characters) for _ in range(length))

Fix:

import random
import string

Using input() without converting to int

input() always returns text.

This is wrong:

length = input("Enter password length: ")

for _ in range(length):
    print("x")

This causes a TypeError because range() needs an integer, not a string. See how to fix TypeError: 'str' object cannot be interpreted as an integer.

Fix:

length = int(input("Enter password length: "))

Choosing a password length of 0

This does not crash, but it gives you an empty password:

import random
import string

length = 0
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))

print(password)

Output:

A simple fix is to check the value first:

if length <= 0:
    print("Please enter a number greater than 0.")

Accidentally reusing variable names like string

Be careful not to overwrite the module name.

Wrong:

import string

string = "hello"
print(string.ascii_letters)

Now string is a normal text value, not the module. That breaks your code.

Use a different variable name instead.


FAQ

How do I generate a password in Python?

Create a string of allowed characters, pick random characters, and join them into one string.

Should I use random or secrets?

Use random for simple learning examples. Use secrets for real password generation.

Why does input length cause an error?

input() returns text. Convert it with int() before using it in range().

How can I include numbers and symbols?

Add string.digits and string.punctuation to the allowed characters.


See also

Try improving this script next by:

  • asking the user for password length
  • adding an option to include symbols
  • making sure the password contains at least one number
  • then building a more secure version with the secrets module