Python Program to Generate Password with Random Characters
random and string modules to generate a password by combining letters, digits, and symbols, for example: import random, string; password = ''.join(random.choice(string.ascii_letters + string.digits + string.punctuation) for _ in range(12)).Examples
How to Think About It
Algorithm
Code
import random import string def generate_password(length=12): chars = string.ascii_letters + string.digits + string.punctuation password = ''.join(random.choice(chars) for _ in range(length)) return password print("Generated password:", generate_password(12))
Dry Run
Let's trace generating a password of length 4 through the code
Import modules
random and string modules are ready to use
Set length
length = 4
Create character set
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
Select characters
random picks: ['G', '7', '#', 'k']
Join characters
password = 'G7#k'
Return password
Output: 'G7#k'
| Iteration | Selected Character |
|---|---|
| 1 | G |
| 2 | 7 |
| 3 | # |
| 4 | k |
Why This Works
Step 1: Importing modules
We use random to pick characters randomly and string to get sets of letters, digits, and symbols.
Step 2: Combining characters
All allowed characters are combined into one string so we can pick from them easily.
Step 3: Generating password
We pick random characters one by one until we reach the desired length, then join them into the final password string.
Alternative Approaches
import secrets import string def generate_secure_password(length=12): chars = string.ascii_letters + string.digits + string.punctuation password = ''.join(secrets.choice(chars) for _ in range(length)) return password print("Secure password:", generate_secure_password(12))
import random import string def generate_simple_password(length=12): chars = string.ascii_letters + string.digits password = ''.join(random.choice(chars) for _ in range(length)) return password print("Simple password:", generate_simple_password(12))
Complexity: O(n) time, O(n) space
Time Complexity
The program runs in O(n) time because it selects one character at a time for the password length n.
Space Complexity
It uses O(n) space to store the generated password string of length n.
Which Approach is Fastest?
Using random.choice is fast and simple, but secrets.choice is more secure though slightly slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| random.choice with letters+digits+symbols | O(n) | O(n) | General use, fast |
| secrets.choice with letters+digits+symbols | O(n) | O(n) | Security-sensitive password generation |
| random.choice with letters+digits only | O(n) | O(n) | Simple passwords, easier typing |
secrets module instead of random for generating passwords in real security applications.