Generate Random Passwords in Python
Complete code tutorial with examples and best practices
[ Code Example - Quick Summary ]
Language: Python
What: Generate secure random passwords in Python using the <code>secrets</code> module for cryptographically secure random generation. Perfect for security-sensitive applications.
Try it: Use our interactive Passwords generator or integrate this code into your Python application.
Generate secure random passwords in Python using the secrets module for cryptographically secure random generation. Perfect for security-sensitive applications.
Looking for other languages? Check our code examples in
PHP
,
JavaScript
,
Java
,
C#
,
C++
,
Ruby
and
Go
or use our interactive web generator.
Python Code Example
import secrets
import string
def generate_password(length=16, include_special=True):
lowercase = string.ascii_lowercase
uppercase = string.ascii_uppercase
numbers = string.digits
special = '!@#$%^&*()-_=+[]{}|;:,.<>?'
chars = lowercase + uppercase + numbers
if include_special:
chars += special
password = ''.join(secrets.choice(chars) for _ in range(length))
return password
# Generate a 16-character password with special characters
password = generate_password(16, True)
print(password) # Example: aB3$xY7!mN2@pQ9&
# Generate a 12-character password without special characters
simple_password = generate_password(12, False)
print(simple_password) # Example: aB3xY7mN2pQ9
[EXPLANATION]
The secrets module is specifically designed for generating cryptographically strong random data suitable for security purposes. secrets.choice() securely selects random characters from the character set.
Expected Output
aB3$xY7!mN2@pQ9& aB3xY7mN2pQ9
Common Use Cases
- Django/Flask web application authentication
- API token and secret key generation
- Password reset functionality
- Security testing and penetration testing scripts
- Command-line password generation tools
- Automated user provisioning systems
Important Notes
-
Use
secretsmodule (Python 3.6+) for passwords -
Avoid using
randommodule for security purposes -
stringmodule provides convenient character sets -
Consider using
secrets.token_urlsafe()for URL-safe tokens
Try Our Interactive Generator
Don't want to write code? Use our free web-based Passwords generator with instant results.
TRY PASSWORDS GENERATOR →Other Programming Languages
View Passwords generation code examples in PHP
View Passwords generation code examples in JavaScript
View Passwords generation code examples in Java
View Passwords generation code examples in C#
View Passwords generation code examples in C++
View Passwords generation code examples in Ruby
View Passwords generation code examples in Go