Generate Password in Python

Generate password in python

You should use the secrets module to generate cryptographically safe passwords, which is available starting in Python 3.6. Adapted from the documentation:

import secrets
import string
alphabet = string.ascii_letters + string.digits
password = ''.join(secrets.choice(alphabet) for i in range(20)) # for a 20-character password

For more information on recipes and best practices, see this section on recipes in the Python documentation. You can also consider adding string.punctuation or even just using string.printable for a wider set of characters.

How to generate random password in python

You can choose a character from a list with the python secrets library. Here is an example:

import string
import secrets

symbols = ['*', '%', '£'] # Can add more

password = ""
for _ in range(9):
password += secrets.choice(string.ascii_lowercase)
password += secrets.choice(string.ascii_uppercase)
password += secrets.choice(string.digits)
password += secrets.choice(symbols)
print(password)

Random password generator with words limit

Use the built-in len function instead and use a while loop:

#input the length of password
#must be minimun 8 to maximun 16

#if use enter less than 8 or more than 16
l = False
while not l:
length = input('\nEnter the length of password: ')
if len(length) < 8 :
print('You password length is too short(must be more than 8 character)')
print(len(length), "is the length of your password")
elif len(length) > 16:
print('You password length is too long(must be less than 17 character)')
print(len(length), "is the length of your password")
else:
print('You password length looks good')
break


Output:

Enter the length of password: thisismorethan16characters
You password length is too long(must be less than 17 character)
26 is the length of your password

Enter the length of password: thisisgood
You password length looks good
>>>

Also, remove the int() so we can allow the user to enter a string, and you usually use return when it's in a function. Also there is no use of ; in python.

Python password generation

simply shuffle the resulting password at the end by adding this:

password = "".join(random.sample(password,len(password)))

This way you meet the requirements without creating a pattern.

or you could shuffle the requirements and write the function like this:

from random  import sample
from secrets import choice
from string import *

def getRandomPassword(length):
alphabet = ascii_letters + digits + punctuation
requirements = [ascii_uppercase, # at least one uppercase letter
ascii_lowercase, # at least one lowercase letter
digits, # at least one digit
punctuation, # at least one symbol
*(length-4)*[alphabet]] # rest: letters digits and symbols
return "".join(choice(req) for req in sample(requirements,length))


Related Topics



Leave a reply



Submit