create a password with uppercase, lowercase letters and numbers in python

In Python, you can generate a password with uppercase, lowercase letters and numbers using the string and random module. Here's an example code snippet:

main.py
import random
import string

def generate_password(length):
    """
    This function generates a random password of given length with uppercase, lowercase letters and numbers.
    """
    # define the possible characters
    upper_case = string.ascii_uppercase
    lower_case = string.ascii_lowercase
    digits = string.digits
    
    # create a pool of characters to choose from
    pool = upper_case + lower_case + digits
    
    # generate a random password of given length
    password = ''.join(random.choice(pool) for i in range(length))

    return password
569 chars
20 lines

In this code, we first import the required modules random and string. The string module has constants ascii_uppercase, ascii_lowercase, and digits which contain all uppercase and lowercase letters, and numbers respectively.

We define a function generate_password that takes a length as an input parameter. It creates a pool of characters by concatenating all uppercase, lowercase letters and digits.

Using random.choice function, it randomly chooses a character from this pool of characters length number of times, and concatenates all the chosen characters to form a password.

Finally, the function returns the generated password.

Example usage:

main.py
password = generate_password(8)
print(password)  # Output: 'Ea0fz8sW'
70 chars
3 lines

gistlibby LogSnag