Python Program to Generate Password

To create a password with Python, we need to create a program that takes the length of the password and generates a random password of the same length. In this article, I’ll walk you through how to write a Python program to generate a password.

Python Program to Generate Password

To write a Python program to create a password, declare a string of numbers + uppercase + lowercase + special characters. Take a random sample of the string of a length given by the user:

enter the length of password7

In the above code, I first imported the random module in Python, then I asked for user input for the length of the password. Then I stored the letters, numbers and special characters that I want to be considered while generating a password. Then I am doing a random sampling by joining the length of the password and the variable s, which will finally generate a random password.

Also, Read – 100+ Machine Learning Projects Solved and Explained.


There are a few areas where the above code could be improved upon, but at a basic level, it meets many secure password generation requirements by today’s standards. As a newbie to Python or any other language, you should keep trying these types of programs as they help you explore more functions and in the long run will help you design your algorithms.

I hope you liked this article on how to write a Python program to generate a password. Feel free to ask your valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1537


  1. Hey Guys, You can also use this code:-

    import random
    p=int(input(“Length of password:- “))
    for i in range(p):

Leave a Reply