Write a Python program to generate a random password

How to generate a random password. There is a way to write a program in Python to generate a random password with some checks Let’s see the Python code to generate the random and new password on every execution.

How to generate a random password?

The password is a blend of letters (lowercase and capitalized), digits, and accentuation. Some worldwide factors to store letters are using lowercase and capitalized, digits and accentuation separately. To accomplish this assignment, Python has a built-in string library which contains a collection of string constants, and using the random function it will generate a random password.

What is a password?

Input: Generate a password

Output: ug792

Algorithm to generate a random password:

  •       Import random.
  •       Assign a variable that will randomly generate letters, punctuation, and digits.
  •       Use join() function to join the randomly generated letters, punctuation, and digits to a new variable.
  •       Print the new variable.

Python program to generate a random password.

Method 1: using join() function

import string
from random import *

char = string.ascii_letters + string.punctuation + string.digits

password=" ".join(choice(char)for x in range(randint(5,16)))

print("Your password is",password)

Output: Printing the randomly generated password in Python

Method 2: Defining the length of the password

import random
alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm','n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
a = 0
length = int(input("Enter the length of your password:"))
if length%2 == 0:
    num = length/2
    for i in range(int(num)):
        a = random.choice(alpha)
        print(a, end = '')
    for i in range(int(num)):
        print(random.randint(0,9), end = '')
else:
    num = length/2
    x = int(num)
    el = length-x
    for i in range(x):
        a = random.choice(alpha)
        print(a, end = '')
    for i in range(el):
        print(random.randint(0,9), end = '')

Output: Printing the randomly generated password