Passwords are very essential things right. Choosing a password for accounts are sometimes becomes boring. So, let’s solve this problem in a pythonic way. Let’s create our own password generator using python.
Goal
We need a secure password right. So, our password contains Digit, Lower and Uppercase alphabets, Symbols. So, first we ask users how much your password long.
Installation
We use these two models, string and random. In case not installed then copy this following command and paste in your terminal/CMD to install.
pip install strings
pip install random
Coding
import both modules.
import string import random
Now, get a-z, A-Z, 0-9, and symbols using string functions provided by string module inbuilt.
s1 = string.ascii_lowercase s2 = string.ascii_uppercase s3 = string.digits s4 = string.punctuation
now, ask user to get password length
plen = int(input("Enter password length: "))
Now, we make list of character we get using string function.
s = [] s.extend(list(s1)) s.extend(list(s2)) s.extend(list(s3)) s.extend(list(s4))
Here, we convert s1,s2,s3, and s4 in list type because above string functions like string.ascii_lowercase return a string. And extend() is used to concrete list. This list looks like this.
['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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~']
So, we get all character in one list. We use this list to get our password. For that we use sample() function to get random character of given length.
sample() is an inbuilt function of a random module in Python that returns a particular length list of items chosen from the sequence i.e. list, tuple, string, or set. Used for random sampling without replacement.
At last, join all character in a list into a string, using a “” character as separator.
print("".join(random.sample(s, plen)))
Final Code
import string import random if __name__ == "__main__": s1 = string.ascii_lowercase s2 = string.ascii_uppercase s3 = string.digits s4 = string.punctuation plen = int(input("Enter password length: ")) s = [] s.extend(list(s1)) s.extend(list(s2)) s.extend(list(s3)) s.extend(list(s4)) print("Your password: ", end="") print("".join(random.sample(s, plen)))
Output
Enter password length: 8
Your password: lrOuGH3^
There are endless possibilities to make this code better. You can add a minimum length password in 8 characters or You can also exclude some character from the symbol list. Endless possibilities right. So this a simple password generator using python.
Also see:
1 thought on “Simple Password Generator using Python”