Alfie brown Alfie brown - 1 month ago 5
Python Question

Python v3 ( Random password generator )

My question is: how to generate a random password with a length that varies from (8 to 12 characters) each time generated.

This is my code:

import string
import random

def randompassword():
chars=string.ascii_uppercase + string.ascii_lowercase + string.digits
size=8
return ''.join(random.choice(chars) for x in range(size,12))

print(randompassword())

Answer

size = 8; range(size, 12) always returns array [8,9,10,11], so you always get a password of length 4. Instead, determine the size of this particular password using randint ahead of time:

import string
import random

def randompassword():
  chars = string.ascii_uppercase + string.ascii_lowercase + string.digits
  size = random.randint(8, 12)
  return ''.join(random.choice(chars) for x in range(size))