Strong Random Password Generator [Python]

Let’s build our own secured random password generator using Python.

Harsha Nanayakkara
4 min readJul 12, 2022

Hello everyone, I hope you are fine and safe 🙂

Today, in this article, I will take you a walk with me to share all relevant details along with a brief explanation of the code. The motive behind this task was to have a password generator for personal use rather than referring to online applications when I need to create new passwords. Also, I used this as an opportunity to learn and improve Python skills as well.

This code covers below requirements;

  • The preferred password length is requested from the user as an input.
  • This code will only work if the password length is ≥ 8 digits.
  • There will be at least one occurrence of each item below in the newly generated password
    - Lower case letter
    - Upper case letter
    - Number
    - Special character

That’s all about the background and requirements which I tried to accomplish using this project. Now let’s take a look at the code.

import secrets
import string
import random

First of all, we need to import the modules shown as above.

The secrets module is used to generate cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets¹. string module is used to work with strings and random is used only to shuffle a list later on. As per Python docs, it is recommended to use the secret module for security and cryptographic uses² which I have used in this practical. Additionally, I have tried to make the code self explanatory by adding comments as well to make it easily understandable.

try:   
password_length = int(input("Please enter length of the password: "))
if password_length >= 8: base_chars = list() #Select 1 lowercase letter
lower = secrets.choice(string.ascii_lowercase)
#Select 1 uppercase letter
upper = secrets.choice(string.ascii_uppercase)
#Select 1 digit
digit = secrets.choice(string.digits)
#Select 1 special char
special = secrets.choice(string.punctuation)
#Add all the selected chars into the list for later use
base_chars.append(lower)
base_chars.append(upper)
base_chars.append(digit)
base_chars.append(special)

The code is inside a try and except block. The user is prompted to enter a suitable number as the required password length. The code will only work if the given length is ≥ 8. A list is created as base_chars . As the next step, one value representing each item has been taken randomly using the built-in functions in secrets and string modules. After getting those values they are added (appended) to the base_chars list.

        #Use combination with lower,upper,special chars and digits
password_combination = string.ascii_letters + string.digits + string.punctuation
#Create remaining chars from the password combination in addition to the previously create 4 chars
remainder_chars = [secrets.choice(password_combination) for _ in range(password_length - 4)]
#Add all the chars to the list
remainder_chars.extend(base_chars)
#For extra layer of security the list values are shuffled
random.shuffle(remainder_chars)
#Create password with the values
password = "".join(remainder_chars)
print(password)

Now, it is time to generate password combination. As per the above code sample, password consists of characters (i.e. both lower and upper), digits and special characters. string.ascii_letters gives both lower and upper case characters [a-zA-Z]. string.digits provides the numbers from 0–9 whereas, string.punctuation returns all the sets of punctuation / special characters [!”#$%&’()*+,-./:;<=>?@[\]^_`{|}~].

remainder_chars = [secrets.choice(password_combination) for _ in range(password_length - 4)]

The above code segment generates remaining characters for the password. As you already know by now, we have created 4 characters earlier. Therefore, here we create the remaining set of characters using the password combination. I have used the _ before in range because I don’t actually concern about the return value. It’s no harm to keep it as i or x or anything you prefer, but I preferred this way 😊. The result is added to a new list called remainder_chars . Then, the result set from the initial list base_chars is added to the remainder_chars list to combine all characters together. Please note that, extend is used here. After that, the list is shuffled using random.shuffle to make it more random. Finally, all the characters in the shuffled list are joined to produce the password. Password is then displayed on the console.

else:
print("Please enter a number greater than or equal to 8")
except:
print("Please enter a valid number")

At the very end of the code, an error message is displayed to the user if the number inserted is lesser than 8 or if anything else other than a number is entered.

Hoorah! We’ve completed our own password generator.

You can also see the code in GitHub. Please feel free to use the code to suit your particular needs.

Sample output is depicted below to illustrate the functionality of the above code.

Outputs of the Python password generator
Password Generator Output

I sincerely hope this guide will help you to make your lives easier. Thank you for reading and stay safe!

References:

¹ https://docs.python.org/3/library/secrets.html
² https://docs.python.org/3/library/random.html

--

--

Harsha Nanayakkara

An enthusiastic autodidact who is passionate to gain and freely share knowledge. I would really appreciate your feedback and support!