create a password generator in python

To create a password generator in Python, you can leverage the random module to generate secure and random strings, then combine them to form a password.

Here's an example code:

main.py
import random

def generate_password(length=8):
    """Generate a random password with the given length"""
    characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+-=[]{}|;:,.<>/?"
    password = ''.join(random.choice(characters) for i in range(length))
    return password
309 chars
8 lines

In this code, we defined a function called generate_password which takes an argument length specifying the desired length of the password. Inside the function, we defined a string called characters which contains all possible characters to be used in the password. Then we used a for loop to generate length random characters from characters, and concatenated them into a string using join() function.

To test this function, you can simply call it with an integer argument representing the desired length, like this:

main.py
password = generate_password(12)
print(password)
49 chars
3 lines

Output:

main.py
$MWV124b2W(X
13 chars
2 lines

Note that you can customize the characters string to include only specific character types if needed, for example to only include lowercase letters and digits:

main.py
characters = "abcdefghijklmnopqrstuvwxyz1234567890"
52 chars
2 lines

related categories

gistlibby LogSnag