In this post, we will create a simple password generator in Python by taking input from the user with a detailed explanation and example.
If you are a beginner, you can consider this as your mini project where you randomly generate passwords. Additionally, this program will help you grasp your logic. So let’s start learning and making password a generator in Python.
But before we jump into the algorithms or programming part few programming concepts you must know:
Algorithm
- Import
random
module - Create three lists, The first one contains a list of alphabets (upper or lowercase both), the second list contains a list of numbers from 0 to 9 and the third one contains a list of special characters such as @, #, $, ^, &, *, etc
- Take user input such as how many characters, numbers, and special characters they want in their password.
- Create an empty list to store your password (
password_list = []
). - Using
for-loop
iterate over user input times in each list and randomly choose characters, numbers, and special characters and append it in empty listpassword_list
- After that join your
password_list
list into the string using thejoin()
method. - print your password.
From the above algorithms, now we know how we will implement a password generator in Python. So let’s start writing code for it.
Source Code
import random
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers =[0,1,2,3,4,5,6,7,8,9]
special_characters = ['!','@','#','$','%','^','&','*','(',')','_','-','+','=']
char_in_password = int(input('How many alphabats you want in your password : '))
number_in_password = int(input('How many numbers you want in your password : '))
special_char = int(input('How many special characters you want : '))
password_list = []
for j in range(1,char_in_password+1):
ch = random.choice(alphabets)
password_list.append(ch)
for k in range(1,number_in_password+1):
num = str(random.choice(number)) # choice method choose random item from list
password_list.append(num)
for l in range(1,special_char+1):
sp = random.choice(special_character)
password_list.append(sp)
random.shuffle(password_list)
password = ''.join(password_list)
print(f'your password is [ {password} ]')
Output-1
How many alphabats you want in your password : 4
How many numbers you want in your password : 3
How many special characters you want : 1
your password is [ B5r2i3#D ]
Output-2
How many alphabats you want in your password : 5
How many numbers you want in your password : 3
How many special characters you want : 1
your password is [ x13U^CXU0 ]