You can download this code by clicking the button below.
This code is now available for download.
This function generates a random password of a specified length using the built-in string and random modules in Python.
Technology Stack : string, random
Code Type : Function
Code Difficulty : Intermediate
import math
import os
import random
import re
import string
def random_password(length=12):
"""
Generate a random password with a given length using the string and random modules.
"""
if not isinstance(length, int) or length < 8:
raise ValueError("Password length must be an integer greater than or equal to 8.")
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for i in range(length))
return password