The Password Generator Python Program Explained

Peace Ikeoluwa Adegbite
6 min readNov 11, 2020

The Password generator Python program generates a random password for the user. The password generated would be a mixture of upper and lower case letters, symbols and numbers. The program gets information from the user on how long they want their password to be and how many letters and numbers they want in their password which must have atleast 6 characters. In this article, I have explained the Password generator Python program.

We start by importing the needed libraries and submodules:

import numpy as np
from numpy.random import choice,shuffle
import pandas as pd
import sys
import string

From the string package, we can get all possible upper and lower case letters, digits and symbols needed for the password. These are printed in the code below:

print(string.ascii_letters,'\n',string.digits,'\n',string.punctuation)#Output
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

We then create lists from these strings and name them letters, numbers and symbols respectively

letters= list(string.ascii_letters)
numbers= list(string.digits)
symbols=list(string.punctuation)

Now let’s create some functions:

checker1 Function

This function ensures that the user enters a password length of atleast 6 characters.

The password length is made a global variable so that it can be used both inside and outside the checker1 function. The checker1 function gets information from the user on how long they want their function to be and saves this as len_pwd. If the password length is less than 6, it prints a message telling the user that the password length must be atleast 6 and tells them to try again. It then calls and runs itself again. If the password length is greater than 6 as required, it moves on to the checker2 function.

The try and except block catches value errors e.g inputing a string instead of an integer and it raises an error message. It also gives the user the opportunity to try again, thus it calls the checker1 function again.

#This function ensures that the user's password length is atleast 6
def checker1():
global len_pwd

try:
len_pwd= int(input('How long do you want your password to be?:\n '))

if len_pwd<6:
print('Your password must have atleast 6 characters. Please try again.')
checker1()
else:
checker2()

except ValueError:
print('Please enter an integer which is greater than 6')
checker1()

checker2 Function

This function checks to avoid arithmetic errors. It ensures that the sum of the number of password letters and numbers entered by the user is not greater than the password length.

The checker2 function gets information on the number of letters and numbers the user wants in his/her password and saves them as no_letters and no_numbers respectively (these are bothglobal variables). It then subtracts the sum of no_letters and no_numbers form the len_pwd in order to obtain the number of symbols that the password will have. This is saved as no_symbols.

If the sum of the of the no_letters, no_symbols and no_numbers is greater than the len_pwd, the function tells the user of this arithmetic error and calls itself again, thereby giving the user the opportunity to enter new inputs. However, if the sum of the of the no_letters, no_symbols and no_numbers is not greater than the len_pwd, as required, it goes on to generate the password using the generate_password function.

The try and except block catches other arithmetic errors and all forms of value errors. The checker2 function is as in the code below:

def checker2():
global no_letters
global no_numbers
global no_symbols

no_letters= int(input('\nHow many letters do you want in your password?:\n'))
no_numbers= int(input('\nHow many numbers do you want in your password?:\n'))
no_symbols= len_pwd - (no_letters + no_numbers)
try:
if (no_letters + no_numbers+ no_symbols) > len_pwd:
print('\nThe number of letters and numbers you want cannot be greater than your password length')
checker2()
else:
generate_password()

except ArithmeticError and ValueError:
print('\nInvalid Input. \nEnsure that the sum of the number of letters and symbols entered is not greater the length of password')
checker2()

generate_password Function

This is the function that actually generates the password. Remember that we earlier created lists of all possible letters, numbers and symbols and named them letters, numbers and symbols respectively.

Using random.choice, we now randomly choose a list of letters. The number of letters chosen from the main ‘letters’ list into the new list will be the number of letters i.e no_letters that was earlier specified by the user in the checker2 function. Using the join method (join method is the inverse of strip method), we them join the items in the randomly chosen, new list into a string. These same steps are repeated for the numbers and symbols such that we now have strings of randomly chosen letters, symbols and numbers whose lengths are as specified by the user. These strings are stored as sample_letters, sample_numbers and sample_symbols. They are then added together to give a single string which is a summation of the sample_letters, sample_numbers and sample_symbols. This single string is named raw_password.

Since random.shuffle can only be applied to lists, we convert the raw_password which is a string to a list named password, and then shuffle it using random.shuffle. After the list is shuffled, it is converted back to a string using the join method. This is the generated password. The function returns the shuffled password, password.

def generate_password():
global password
sample_letters=''.join(choice(letters,no_letters))
# You can also use: ''.join(secrets.SystemRandom().choice(letters) for i in range(no_letters))
sample_numbers= ''.join(choice(numbers,no_numbers))
sample_symbols= ''.join(choice(symbols,no_symbols))
raw_password=sample_letters + sample_numbers + sample_symbols

password=list(raw_password)
shuffle(password)
password=''.join(password)

return(password)

switch Function

This function allows the user to generate a new password or not depending on the user input. The function asks if the user wants to generate a new password or not and saves the user input as on. on is a global variable. It is then converted to lowercase using the lower method so that the function is not affected by whatever case (uppercase or lowercase) the user chooses to use. If on is equal to ‘yes’, the main function is called and executed, if not, the system is shut down.

If the user enters an invalid input, it prints an error message and then, calls itself again. The try and except block catches value errors.

def switch():
global on
try:
print('\nDo you want to generate another password?')
on= input('\nPlease enter Yes or No \n').lower()
on= on.lower() #This turns the user's input to lowercase
if on=='yes':
main()
elif on=='no':
sys.exit()
else:
print('\nInvalid Input. Enter yes or no')
switch()
except ValueError:
print('\nInvalid Input')
sys.exit()

main Function

This is the starting function, it is the entry point. It is the point of execution where the password is actually printed. The main function welcomes the user and calls the checker1 function which checks its specified condition. If this condition is satisfied, the checker1 function calls the checker2 function which also checks its specified condition, if its condition is satisfied, it then calls the generate password function which returns the password. The main function prints the password and calls the switch function to check if the user wants to generate another password.

def main():
print('\nWelcome! :-) \nThis program will help you to generate a password.')
checker1()

print('\nYour password is: {}'.format(password))
switch()

Below is an example of the execution of this program:

main()#Output
Welcome! :-)
This program will help you to generate a password.
How long do you want your password to be?:
4
Your password must have atleast 6 characters. Please try again.
How long do you want your password to be?:
12

How many letters do you want in your password?:
5

How many numbers do you want in your password?:
2

Your password is: @K\4QCg(?6f!

Do you want to generate another password?

Please enter Yes or No
123

Invalid Input. Enter yes or no

Do you want to generate another password?

Please enter Yes or No
YES

Welcome! :-)
This program will help you to generate a password.
How long do you want your password to be?:
7

How many letters do you want in your password?:
23

How many numbers do you want in your password?:
13

Invalid Input.
Ensure that the sum of number of letters and symbols entered is not greater the length of password

How many letters do you want in your password?:
2

How many numbers do you want in your password?:
4

Your password is: 1RO%662

Do you want to generate another password?

Please enter Yes or No
no

SystemExit

--

--