You can download this code by clicking the button below.
This code is now available for download.
This function is used to generate a random password of a specified length, which can include letters, numbers, and special characters.
Technology Stack : random, string, ValueError
Code Type : Generate random password
Code Difficulty : Intermediate
import random
import os
import json
import re
import string
import math
import datetime
def generate_random_password(length, use_special_chars=True):
if length < 8:
raise ValueError("Password length must be at least 8 characters.")
characters = string.ascii_letters + string.digits
if use_special_chars:
characters += string.punctuation
password = ''.join(random.choice(characters) for i in range(length))
return password