Python Random Password Generator
Generate secure, random passwords in Python. Learn to use the random module alongside string constants to build robust security tools.
How it Works
Password generators require accessing random number functions and mapping them to ASCII character sets.
The Python standard library provides `random` and `secrets` to perform unbiased random selections.
For cryptographic or high-security needs, Python’s `secrets` module is preferred over `random` as it is cryptographically strong.
Source Code
Combining uppercase, lowercase, numbers, and symbols to output a 16-character secure string.
password_gen.py
Try in Editorimport random
import string
def generate_password(length=12):
# Combine all character sets
characters = string.ascii_letters + string.digits + string.punctuation
# Randomly select characters until the desired length
password = ''.join(random.choice(characters) for _ in range(length))
return password
print("Generating 3 secure passwords:")
for i in range(3):
print(f"Password {i+1}: {generate_password(16)}")Terminal Output
Generating 3 secure passwords:
Password 1: a!7T#nP@zQ8k*L1w
Password 2: xY9^vB4$mC2&pR5j
Password 3: dF3%hK6*tW9@nM1q
(Output will be random during real execution)Real-world Applications
- Automated user credential assignment
- Generating mock data for penetration testing suites
- System admin utility scripts for server deployment
Frequently Asked Questions
Is the `random` module safe for real passwords?
The `random` module is pseudo-random. For generating actual secure passwords in production, you should use Python’s `secrets` module which utilizes OS-level secure entropy.
More Examples
Python Simple Calculator Script
Build a basic calculator in Python. Learn how to map mathematical operators, take user execution flows, and handle logic natively.Python Number Guessing Game
A classic beginner Python project. Build an interactive number guessing game that uses random generation, while loops, and user input validation.