How to Make a Password Generator in Python

Published on Aug. 22, 2023, 12:16 p.m.

Here’s a simple example of how to make a password generator in Python:

import random
import string

def generate_password(length):
    alphabet = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(random.choice(alphabet) for i in range(length))
    return password

length = int(input("Enter the length of the password: "))
password = generate_password(length)
print("Your password is:", password)

In this code, we first import the random and string modules to generate random passwords. We define a function called generate_password that takes a length parameter and generates a random password of that length.

Inside the function, we define an alphabet that includes letters, numbers, and punctuation using the string module. We then use a loop and random.choice to choose random characters from the alphabet and concatenate those characters to form a password.

We then ask the user to enter the length of the password, call the generate_password function with that length parameter, and finally print the generated password.

This is just a simple example, and there are many possible variations and improvements you could make to a password generator.

Tags:

related content