A password generator is a small program with clear requirements and several useful edge cases. You will build one that lets the user choose a length and character sets, then produce a password and a short strength report.
What you will build#
A console tool that:
- Asks for a password length.
- Asks whether to include digits and symbols.
- Validates the choices.
- Generates a password containing at least one character from each selected set.
- Prints the password and its length.
- Refuses lengths below 8 and above 128.
Character sets#
import string
lowercase = string.ascii_lowercase
uppercase = string.ascii_uppercase
digits = string.digits
symbols = "!@#$%^&*()-_=+[]{};:,.?/"Keep the sets explicit. Do not include ambiguous lookalike characters such as O, 0, l, and 1 in a password meant for manual entry unless the user asks for them.
A first generator#
import random
alphabet = lowercase + uppercase + digits
length = 12
password = "".join(random.choice(alphabet) for _ in range(length))
print(password)random.choice() picks one character. The generator expression runs once per position.
Guaranteeing character variety#
Choosing independently from the full alphabet can produce a password with no digits, even when digits are enabled. Guarantee one from each required set, then fill the remainder:
def generate_password(length, required_sets):
if length < len(required_sets):
raise ValueError("Length is too short for the selected character sets")
characters = [random.choice(characters_set) for characters_set in required_sets]
alphabet = "".join(required_sets)
while len(characters) < length:
characters.append(random.choice(alphabet))
random.shuffle(characters)
return "".join(characters)Shuffling matters: without it, the first characters always come from known sets, which leaks structure.
Using secrets#
random is not designed for security-sensitive tokens. Use the secrets module when the password protects a real account:
import secrets
def secure_password(length, required_sets):
characters = [secrets.choice(characters_set) for characters_set in required_sets]
alphabet = "".join(required_sets)
while len(characters) < length:
characters.append(secrets.choice(alphabet))
secrets.SystemRandom().shuffle(characters)
return "".join(characters)secrets.choice() uses the operating system's secure random source. secrets.SystemRandom().shuffle() shuffles securely. The generator still needs the same validation.
Validation#
def read_length():
text = input("Password length (8-128): ").strip()
try:
length = int(text)
except ValueError:
print("Enter a whole number.")
return None
if not 8 <= length <= 128:
print("Length must be between 8 and 128.")
return None
return lengthAsk for yes/no options explicitly and default to safe values:
use_digits = input("Include digits? (y/N): ").strip().lower() == "y"
use_symbols = input("Include symbols? (y/N): ").strip().lower() == "y"Only y enables an option, so pressing Enter keeps it off. This is a safer default than treating any answer as yes.
Strength report#
Avoid claiming a password is "unbreakable" or assigning an exact crack time. State what the generator knows:
pool_size = len(alphabet)
entropy_bits = length * (pool_size.bit_length())
print(f"Length: {length}")
print(f"Character pool: {pool_size}")
print(f"Approximate entropy: {entropy_bits} bits")This rough estimate assumes every character is chosen independently from a uniform alphabet. The guarantee step changes the distribution slightly, so label the number approximate. For a precise audit, use a dedicated password-strength library in a full Python environment.
Testing checklist#
- Generate a 12-character password with digits and symbols.
- Verify the length is exactly 12.
- Confirm at least one digit and one symbol when selected.
- Try length
7,129,abc, and a blank line. - Generate several passwords and confirm they differ.
- Check the all-letters configuration.
Stretch goals#
- Add a passphrase mode that joins random words from a list.
- Exclude ambiguous characters with an option.
- Copy the password to the clipboard with
pyperclipin a local environment. - Write a function that measures unique characters and repeated runs.
- Compare
randomandsecretsoutput distributions with a large sample.
