Random Password Generator in Python

Generate a strong password. Your password may contain letters both in uppercase or lowercase. It also contains numbers and special characters.

To select a random character from a string module using import random. In the meantime, we will discuss how random and string modules are getting part in generating a password.

Random Module

To create a random number, you will need to import the random module using import random. In the random module, you can use the randint to generate a random number.

# Random Number

import random 
random_num = random.randint(0,10)
print(random_num)

In randint, The first parameter will be the starting number and the last parameter will be the ending number. Every time you run the code, you will see a different number between 0 to 10.

String Module

It is not just the string type variable. Instead, It has a lot of extra functionalities. That is, you can use ASCII (American Standard Code for Information Interchange) letters in both uppercase and lowercase and also access all digits using this string module.

# string module 

import string
print(string.digits)
print(string.ascii_letters)
print(string.punctuation)

#Output
0123456789
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

Password Generator 1

To select a random character from a string. you can import random. Then, use the random.choice method. This method is used to select a character from the string.

# Password Generator

import string
import random
 
def generate_password(length):
    all_char = string.ascii_letters + string.digits + string.punctuation
    password = ''
    for char in range(length):
        rand = random.choice(all_char)
        password = password + rand
    return password
 
length = int(input('How many characters in your password?'))
print('Your new password: ',generate_password(length))

Every time you run the code, you will get different characters for a given length.

Password Generator 2

In the above program, we generate a random password using the random and string module. Now, we will generate passwords only using a random module.

#Random Password Generator

import random

lower =  "abcdefghijklmnopqrstuvwxyz"
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers = "0123456789"
symbols = "[]{}()*;/,._-"

all = lower + upper + numbers + symbols
length = int(input("Enter the length of your password"))

password = "".join(random.sample(all, length)) 
print(password)

Each time you run the code, you will get different characters for a given length.

Related Blogs

Auto Typing Code in Python | just 2 lines: https://iterathon.tech//auto-typing-code-in-python-just-2-lines/

LEARN MORE ❣

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *