Table of Contents
What You’ll Build
In this mini project, you’ll create a Python program that generates random passwords for you.
By the end of this chapter, you will:
- Decide what makes a “good” password
- Design a simple password generator
- Implement it step by step
- Improve it with options (length, character types)
- Add simple checks to avoid very weak passwords
We’ll focus on putting together things you already know: variables, strings, loops, if statements, and random numbers.
Planning the Password Generator
Before writing any code, decide what your program should do.
Basic requirements
Our first version will:
- Ask the user how long the password should be (number of characters)
- Generate a random password of that length
- Show the password to the user
We’ll start simple: letters (both lowercase and uppercase) and digits.
So a password might look like:
aX9pT3L0ngPa55w0rdmQ4z2H1x
Later, we’ll add:
- Special characters like
!@#$%&*? - Checks for minimum length
- Options to choose what kinds of characters to include
Choosing Characters for the Password
A password is just a string made from a set of allowed characters.
Character sets
We can define some character sets as strings:
lowercase = "abcdefghijklmnopqrstuvwxyz"
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "0123456789"
symbols = "!@#$%&*?"To build our pool of possible characters, we can combine strings:
all_chars = lowercase + uppercase + digits
Now all_chars contains all the characters we might use in our password.
Example of what all_chars might look like:
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Using `random` to Pick Characters
To build a password, we need to randomly pick characters from all_chars.
We’ll use the random module:
import random
all_chars = "abc123"
random_char = random.choice(all_chars)
print(random_char) # could be 'a', 'b', 'c', '1', '2', or '3'
random.choice(some_string) picks one random character from that string.
To build a password of length n, we can:
- Start with an empty string:
password = "" - Repeat
ntimes: - Pick a random character from
all_chars - Add (
+) it topassword
First Version: Simple Password Generator
Let’s put this together into a small script.
Features:
- Asks for password length
- Generates a random password using letters and digits
- Prints the result
import random
# 1. Define the characters we can use
lowercase = "abcdefghijklmnopqrstuvwxyz"
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "0123456789"
all_chars = lowercase + uppercase + digits
# 2. Ask the user for the password length
length_text = input("How long should the password be? ")
length = int(length_text)
# 3. Build the password
password = ""
for _ in range(length):
random_char = random.choice(all_chars)
password += random_char
# 4. Show the password
print("Your password is:", password)Try running this and generate a few passwords.
Handling Invalid Lengths
Your program will crash if the user types something that’s not a number, or gives a number that’s too small.
Let’s handle some simple cases:
- If the user types a non-number → we’ll show a message and exit
- If the length is less than a minimum (for example, 4) → we’ll warn and ask again or stop
To keep it simple, we’ll:
- Use
try/exceptfor conversion errors - Check that the length is at least 4
import random
lowercase = "abcdefghijklmnopqrstuvwxyz"
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "0123456789"
all_chars = lowercase + uppercase + digits
length_text = input("How long should the password be? ")
try:
length = int(length_text)
except ValueError:
print("Please enter a valid number next time.")
quit()
if length < 4:
print("Password should be at least 4 characters long.")
quit()
password = ""
for _ in range(length):
password += random.choice(all_chars)
print("Your password is:", password)Adding Special Characters (Symbols)
Many websites require special characters. Let’s add them as an option.
We’ll:
- Ask the user if they want to include symbols
- If they say yes, we add symbols to
all_chars - Otherwise, we keep using only letters and digits
import random
lowercase = "abcdefghijklmnopqrstuvwxyz"
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "0123456789"
symbols = "!@#$%&*?"
# Ask user about password length
length_text = input("How long should the password be? ")
try:
length = int(length_text)
except ValueError:
print("Please enter a valid number next time.")
quit()
if length < 4:
print("Password should be at least 4 characters long.")
quit()
# Ask whether to include symbols
use_symbols = input("Include symbols (!@#$%&*?)? (y/n): ")
all_chars = lowercase + uppercase + digits
if use_symbols.lower() == "y":
all_chars += symbols
# Build the password
password = ""
for _ in range(length):
password += random.choice(all_chars)
print("Your password is:", password)Test it twice:
- Once with
y(symbols allowed) - Once with
n(symbols not allowed)
Ensuring Password Has a Mix of Characters
The previous version can still create passwords that are not very strong, for example:
- Only lowercase letters
- Only digits
You might want to ensure that the password has at least:
- One lowercase letter
- One uppercase letter
- One digit
- (Optional) One symbol (if symbols are used)
Strategy
- Decide which character groups must be included
- Pick at least one character from each required group
- Fill the remaining characters randomly from the full pool
- Shuffle the final password so required characters aren’t always at the start
We’ll need another function from random: random.shuffle.
It works with lists, so we’ll:
- Build the password as a list of characters
- Shuffle the list
- Join it into a string at the end
Stronger Password Generator Version
Here is an improved version that tries to include:
- At least one lowercase
- At least one uppercase
- At least one digit
- At least one symbol (if
use_symbols == "y")
import random
lowercase = "abcdefghijklmnopqrstuvwxyz"
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "0123456789"
symbols = "!@#$%&*?"
length_text = input("How long should the password be? ")
try:
length = int(length_text)
except ValueError:
print("Please enter a valid number next time.")
quit()
if length < 4:
print("Password should be at least 4 characters long.")
quit()
use_symbols = input("Include symbols (!@#$%&*?)? (y/n): ")
# Collect the character groups we will use
char_groups = [lowercase, uppercase, digits]
if use_symbols.lower() == "y":
char_groups.append(symbols)
# Build the pool of all possible characters
all_chars = ""
for group in char_groups:
all_chars += group
# 1) Start by making sure we include at least one character from each group
password_chars = []
for group in char_groups:
password_chars.append(random.choice(group))
# 2) Fill the rest of the password with random characters from the full pool
while len(password_chars) < length:
password_chars.append(random.choice(all_chars))
# 3) Shuffle the characters so required ones are not always at the front
random.shuffle(password_chars)
# 4) Join the list into a string
password = "".join(password_chars)
print("Your strong password is:", password)Try running this version multiple times and notice:
- You always get at least one lowercase, one uppercase, and one digit
- If you choose to include symbols, you always get at least one symbol
- The order is random because of
random.shuffle
Extra Ideas and Enhancements
Here are some ways you can extend this project.
1. Difficulty levels
Let the user choose a difficulty level:
1= only letters2= letters and digits3= letters, digits, and symbols
You could ask:
level = input("Choose level (1 = letters, 2 = letters+digits, 3 = strong): ")
Then build char_groups based on the level.
2. Generate multiple passwords at once
Ask the user how many passwords to generate, then use a loop to print several different passwords:
count_text = input("How many passwords do you want? ")
count = int(count_text)
for _ in range(count):
# generate one password (reuse your existing logic)
print("Password:", password)(You’d move your password-creation logic into a function or inner block.)
3. Avoid confusing characters
Some characters look similar:
Oand0land1
You can remove them from your character sets if you want more readable passwords.
Example: Use
uppercase = "ABCDEFGHJKLMNPQRSTUVWXYZ" # no I or O
digits = "23456789" # no 0 or 14. Copying or saving passwords
For now, you’re just printing the password, but you could:
- Save it to a text file (with a warning about security)
- Display it in a nicer format (e.g., with labels like “Website: …, Password: …”)
Summary
In this mini project, you:
- Planned what a password generator should do
- Built a basic version using letters and digits
- Handled user input and simple validation for length
- Added options for symbols
- Ensured the password contains a mix of character types
- Used the
randommodule (choice,shuffle) to create random passwords
This project is a good example of combining many Python basics into a practical tool. As practice, try adding one or two of the extra ideas and see how far you can customize your own password generator.