Python Program To Generate A Random Password

In this tutorial, we will be looking at a Python program that is able to generate a random password. We will make a strong password with the combination of alphabets, numbers and symbols. The following python concepts will come in handy for this tutorial:

Generate Random Password

We will be using random module and string module for this program.

# Importing modules
import string
import random 

# Set of possible characters 
char = string.ascii_letters + string.punctuation + string.digits

# Creating password of random size and displaying it
password =  "".join(random.choice(char) for i in range(random.randint(6, 16)))

In this code, we have started by importing 2 modules – String and Random. To import these modules we use import string and import random. String module has functions that help us define the character set. You can learn more about the Python string module here. Here, the random module is used to generate a random length. You can learn more about the Python random module here.

Our password will include any letter (upper or lower), digits and symbols. To use these we make a string of all of theses. We use String functions to do so. String.ascii_letters represents all the letters, string.punctuation reprsents symbols and string.digits represents digits. We concatenate them to make a string with all these.

string.ascii_letters –> “abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ”

string.punctuation –> ” !”#$%&'()*+,-./:;<=>[email protected][]^_`{|}~”

string.digits –> “0123456789”

Now to create a password which is random and strong. We will make it of random length and also the choice of characters will be random. We choose random characters using random.choice(char). This random choosing happens 6 – 16 times, i.e. the length of the password is 6 to 16 characters long. This random length is chosen using random.randint(6, 16) which finds a random integer in the given range.

We make an empty string using “”, and then use .join to add this string of random characters to it so that our password is of string type. We add characters one by one using a for loop. This loop runs the number chosen by the randint() function.

Now we display the password using print(password).

NOTE: You can edit the character set and this will help you dilute down the password to more sensible outputs. This example is just to show how to use all the functionalities of strings.





So here it is a very simple python program to generate a random password in python.

Also read,

Leave a Reply

Your email address will not be published. Required fields are marked *