How does my computer generate passwords?

step 1: Import the modules.

import random
import string

step 2: Import the letters, numbers and characters you will use

letters = string.ascii_letters  (uppercase and lowercase letters) 
numbers = string.digits (numbers 0-9)
char = string.punctuation (the special characters e.g #@)

step 3: The user will input the number of letters, numbers and characters they want in their passwords.

no_of_letters = int(input('How many letters would you like in your password? '))no_numbers = int(input('How many numbers would you like in your password? '))no_char = int(input('How many characters would you like in your password? '))

step 4: Depending on the number of letters, number and characters that the user inputs, generate an equal number of characters

password = ""
for letter in range (no_of_letters):
random_letter = random.choice(letters)
password += random_letter

#debugging code~
# print(type(random_letter))

for num in range(no_of_numbers):
random_number = random.choice(numbers)
password += random_number

for char in range(no_of_symbols):
random_symbol = random.choice(character)
password += random_symbol
  • We start off with the password as an empty string.
  • We will then incorporate the for loop to loop through the letters/numbers/characters in the range that the user inputs .
  • I also executed a debugging code to ensure that the random_letter variable is a string type before concatenating(joining) to the original empty string.

step 5: Shuffle the string so that your password will not appear in any specific order.

password = random.sample(password, len(password))
final_password = ''.join(password)

#We need to shuffle the password in order that they don't appear in any specific order.
#The .shuffle() fuction doesn't work on strings. We will convert the password to a list, shuffle and then back to a string



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abigael Nyakara

Abigael Nyakara

Data Science Made Easy!. I explain data science concepts in a way that is easy to understand using relatable examples and example code.