Information Security 7 min read

Generating Random Passwords with Python's Random Module

This tutorial demonstrates how to use Python's Random module to generate customizable, secure passwords by selecting character types, specifying length, and shuffling the result, complete with full source code and step-by-step explanations.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Generating Random Passwords with Python's Random Module

Many websites require passwords that contain uppercase letters, lowercase letters, digits, and special symbols, which can be cumbersome to create manually. This article provides a Python exercise that uses the random module to generate random passwords meeting those requirements.

Random module overview : The random module offers functions for generating random numbers and selecting random elements. Two functions are highlighted:

<code>print(random.choice('0123456789'))  # Example output: 3
print(random.choice('0123456789'))  # Example output: 6</code>

The random.choice() function selects a random element from a sequence. Another useful function is random.shuffle() , which shuffles a list in place:

<code>l = [1, 2, 3, 4]
print(l)               # Output: [1, 2, 3, 4]
random.shuffle(l)
print(l)               # Output: e.g., [2, 1, 4, 3]</code>

Character sets : Four basic character groups are defined and stored in a list for easy access.

<code>digits = '0123456789'
letters_low = 'abcdefghijklmnopqrstuvwxyz'
letters_high = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
special = '.@$!%*#_~?&^'

all_letters = [digits, letters_low, letters_high, special]</code>

Input validation : The user specifies the desired password length ( pw_num ) and the number of character types to include ( class_letter ). The script checks that class_letter is between 1 and 4 and that the password length is at least as large as the number of character types.

<code>pw_num = int(input('Enter desired password length: '))
class_letter = int(input('Enter number of character types (digits, lowercase, uppercase, special): '))
if class_letter > 4 or class_letter < 1:
    print('Please choose a type count between 1 and 4!')
    return
elif pw_num < class_letter:
    print('Password length must be greater than or equal to the number of types!')
    return</code>

Building the password : An empty list password stores the characters, and current_letters aggregates all selected character groups. The script first ensures that each chosen type contributes at least one character, then fills the remaining length with random selections from the combined set, and finally shuffles the list.

<code>password = []
current_letters = ''
for i in range(class_letter):
    t = random.choice(all_letters[i])
    password.append(t)               # guarantee at least one of each type
    current_letters += all_letters[i]

pw_num -= class_letter               # remaining characters to add
for i in range(pw_num):
    password.append(random.choice(current_letters))

random.shuffle(password)
print(''.join(password))</code>

Complete script :

<code>import random

digits = '0123456789'               # digits
letters_low = 'abcdefghijklmnopqrstuvwxyz'  # lowercase
letters_high = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # uppercase
special = '.@$!%*#_~?&^'            # special characters

all_letters = [digits, letters_low, letters_high, special]

def get_password():
    pw_num = int(input('Enter desired password length: '))
    class_letter = int(input('Enter number of character types (digits, lowercase, uppercase, special): '))
    if class_letter > 4 or class_letter < 1:
        print('Please choose a type count between 1 and 4!')
        return
    elif pw_num < class_letter:
        print('Password length must be greater than or equal to the number of types!')
        return

    password = []
    current_letters = ''
    for i in range(class_letter):
        t = random.choice(all_letters[i])
        password.append(t)
        current_letters += all_letters[i]

    pw_num -= class_letter
    for i in range(pw_num):
        password.append(random.choice(current_letters))

    random.shuffle(password)
    print(''.join(password))

if __name__ == '__main__':
    get_password()</code>

Running this program will generate a random password that satisfies the specified length and includes the chosen character categories, providing a quick way to create secure passwords.

securityTutorialpassword-generatorRandom
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.