Random Password Generator with Input Constraints

  • Share this:

Code introduction


This function generates a new password randomly based on the input password and specified minimum and maximum lengths.


Technology Stack : Django, random, string

Code Type : Function

Code Difficulty : Intermediate


                
                    
def randomize_password_length(password, min_length=8, max_length=20):
    import random
    import string
    
    if not isinstance(password, str):
        raise ValueError("Password must be a string.")
    
    password_length = random.randint(min_length, max_length)
    new_password = ''.join(random.choices(string.ascii_letters + string.digits, k=password_length))
    return new_password