Skip to main content

Password Generator

In this guide, we'll walk through the process of creating a password generator using Python. This application allows users to generate passwords of varying complexities, helping them enhance their security practices. We’ll cover the essential steps, including input handling, password generation based on user choices, and a user-friendly interface.

Step 1: Setting Up Your Environment

Ensure you have Python installed on your system. You can download it from python.org. Use any text editor or integrated development environment (IDE) like VSCode or PyCharm to write your code.

Step 2: Import Required Libraries

At the start of your script, import the necessary libraries: os, sys, random, and string.

import os
import sys
import random
import string

Step 3: Create the Password Generation Function

Next, we’ll create the generate_password function, which generates a password based on the chosen complexity and length.

def generate_password(complexity, length):
while True:
if complexity == '1': # Weak
characters = string.ascii_letters
elif complexity == '2': # Medium
characters = string.ascii_letters + string.digits
elif complexity == '3': # Strong
characters = string.ascii_letters + string.digits + string.punctuation
elif complexity == '4':
print('\nThank you and have a great day!\n')
sys.exit()
else:
print('\nError: Invalid Choice.')
break

password = ''.join(random.choice(characters) for _ in range(length))
return password

Step 4: Handle User Input

We need a function to get the password length and complexity level from the user. The user_input function handles this.

def user_input():
while True:
try:
length = int(input("\nPassword length (min. 8 max. 64):\n>> "))
break
except ValueError:
print('\nError: Password length must be a number.\n')
return

if length <= 7 or length >= 65:
print('\nError: Invalid range.\n')
return

print("Select complexity level:")
print("[1] Weak")
print("[2] Medium")
print("[3] Strong")
print("[4] Quit")
choice_complexity = input('Your choice: ')

if choice_complexity not in ("1", "2", "3", "4"):
pass

password = generate_password(length=length, complexity=choice_complexity)
if password is None:
print('')
else:
print('\nYour password is:', password)
print()

Step 5: Build the Main Function

Create the main function to present the application header, clear the console, and handle user interaction.

def main():
os.system('cls' if os.name == 'nt' else 'clear')
app_name = 'Password Generator - mkeithx'
border_length = len(app_name) + 4

print("+" + "-" * (border_length - 2) + "+")
print(f" {app_name} ")
print("+" + "-" * (border_length - 2) + "+")
print()
user_input()

while True:
response = input('Do you want to continue? (Y/N) ')
if response.lower() == 'y':
main()
elif response.lower() == 'n':
print('\nThank you and have a great day!\n')
sys.exit()
else:
print('\nError: Please select Y or N.\n')
continue

Step 6: Execute the Program

Ensure the main function runs when the script is executed:

if __name__ == '__main__':
main()

Congratulations!

You've successfully created a password generator in Python! This application allows users to generate passwords of varying complexities, enhancing their security practices. You can further improve this generator by adding features like password strength validation or saving generated passwords securely. Happy coding!