Python Code to Generate a Random Password

A good password is long and random. In Python you can generate one with the secrets module, which is made for passwords and tokens.

Python function to generate a password

import secrets
import string

def generate_password(length=12):
    chars = string.ascii_letters + string.digits + "!@#$%"
    return "".join(secrets.choice(chars) for _ in range(length))

print(generate_password())
print(generate_password(16))

Sample output (the password is random, so yours will be different):

Tutorials Class - Output Window

k9Fz@Tq2LmB8
Xw3#Pq9mZc7!Rv2d

How it works

  • string.ascii_letters has all upper and lower case letters, and string.digits has 0 to 9.
  • secrets.choice() picks one random character from the text.
  • The generator expression picks length characters, and "".join() joins them into a string.
Note: Do not use the random module for passwords. It is not secure enough, because its values can be predicted. Use secrets.

Related: Python Modules and Python Strings.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.