Random Password Generator

  • Share this:

Code introduction


This function generates a random password of a specified length, which can include numbers, uppercase and lowercase letters. By default, the password includes all types, but these can be controlled via parameters.


Technology Stack : re (regular expressions), math (mathematical functions), random (random number generation), string (string operations)

Code Type : Generate random password

Code Difficulty : Intermediate


                
                    
import re
import math
import os
import random
import datetime
import statistics
import sys
import time
import unittest

def generate_random_password(length, use_numbers=True, use_uppercase=True, use_lowercase=True):
    if length < 8:
        raise ValueError("Password length should be at least 8 characters.")
    
    characters = 'abcdefghijklmnopqrstuvwxyz'
    if use_numbers:
        characters += '0123456789'
    if use_uppercase:
        characters += characters.upper()
    if not use_lowercase and not use_numbers and not use_uppercase:
        raise ValueError("At least one character type must be selected.")
    
    random_password = ''.join(random.choice(characters) for i in range(length))
    return random_password