Random Password Generator with Special Characters Option

  • Share this:

Code introduction


This function generates a random password of a specified length, with an option to include special characters.


Technology Stack : math, random, string, sys

Code Type : Generate random password

Code Difficulty : Intermediate


                
                    
import math
import random
import string
import sys

def generate_random_password(length, use_special_chars=False):
    if length < 4:
        raise ValueError("Password length should be at least 4 characters.")
    
    characters = string.ascii_letters + string.digits
    if use_special_chars:
        characters += string.punctuation

    return ''.join(random.choice(characters) for i in range(length))