In today’s digital world, password security is more important than ever. Weak or reused passwords can make your online accounts vulnerable to hacking.
In this tutorial, we’ll build a secure random password generator in Python using the built-in secrets and string modules.
This project is simple, beginner-friendly, and teaches you how to handle user input, loops, error handling, and random data generation safely.
The Complete Code
import secrets
import string
def generator_password():
def generator_print(pass_length, special_char):
password_to_create = ""
while len(password_to_create) != pass_length:
password_to_create += secrets.choice(special_char)
return f"Generated password: {password_to_create}"
while True:
try:
password_length = int(
input("Enter length of your password (at least 8 characters): ")
)
if password_length >= 8:
break
print("Password length must be at least 8 characters.")
continue
except ValueError:
print("Please enter a valid number.")
while True:
include_special = input(
"Include special characters? (yes/no): "
).lower()
if include_special == "yes":
chars = string.punctuation + string.ascii_letters + string.digits
print(generator_print(password_length, chars))
elif include_special == "no":
chars = string.ascii_letters + string.digits
print(generator_print(password_length, chars))
else:
print("Invalid answer. Please type 'yes' or 'no'.")
continue
break
generator_password()
Step-by-Step Explanation
Importing Modules
import secrets
import string
-
secrets: Used for generating cryptographically secure random numbers. -
string: Provides useful character sets like letters, digits, and punctuation.
Defining the Main Function
def generator_password():
All the logic of the password generator is written inside this function.
Inner Function for Password Generation
def generator_print(pass_length, special_char):
password_to_create = ""
while len(password_to_create) != pass_length:
password_to_create += secrets.choice(special_char)
return f"Generated password: {password_to_create}"
-
This inner function creates the password.
-
It randomly picks characters (using
secrets.choice) until the required length is reached. -
Returns the generated password as a formatted string.
Taking Password Length Input
while True:
try:
password_length = int(input("Enter length of your password (at least 8 characters): "))
if password_length >= 8:
break
print("Password length must be at least 8 characters.")
continue
except ValueError:
print("Please enter a valid number.")
-
This loop ensures the user inputs a valid number.
-
The program repeats until the user provides a number ≥ 8.
Asking for Special Characters
while True:
include_special = input("Include special characters? (yes/no): ").lower()
-
Converts user input to lowercase for easy comparison.
-
If yes, it includes punctuation (like
@, #, $, !) in the password. -
If no, it only uses letters and digits.
Generating and Displaying the Password
Depending on the user’s choice:
if include_special == "yes":
chars = string.punctuation + string.ascii_letters + string.digits
print(generator_print(password_length, chars))
elif include_special == "no":
chars = string.ascii_letters + string.digits
print(generator_print(password_length, chars))
Finally, the password is generated and displayed on the screen.
Flowchart Explanation
Below is the logical flow of the program:
┌──────────────────────────────┐
│ Start Program │
└──────────────┬───────────────┘
│
▼
┌──────────────────────────────┐
│ Ask user for password length │
└──────────────┬───────────────┘
│
▼
┌────────────────────┐
│ Is input valid? │
└───────┬────────────┘
│Yes
▼
┌────────────────────┐
│ Length >= 8 ? │
└───────┬────────────┘
│Yes
▼
┌──────────────────────────────┐
│ Ask: Include special chars? │
│ (yes/no) │
└──────────────┬───────────────┘
│
▼
┌────────────────────┐
│ yes → letters + │
│ digits + symbols │
└────────┬───────────┘
│
│no
▼
┌────────────────────┐
│ letters + digits │
└────────┬───────────┘
│
▼
┌──────────────────────────────┐
│ Randomly generate characters │
│ until password is complete │
└──────────────┬───────────────┘
│
▼
┌──────────────────────────────┐
│ Print the generated password │
└──────────────┬───────────────┘
│
▼
┌──────────────────────────────┐
│ End │
└──────────────────────────────┘
Key Learnings
✅ Using secrets for secure randomness
✅ Validating user input with try–except
✅ Combining letters, digits, and symbols to make a strong password
✅ Applying loops and conditional logic in Python