Password Generator
What you'll build
A Python script that generates random passwords with configurable length, character types (letters, digits, symbols), and strength checking.
Goals
- Use the random and string modules for character selection
- Build a function with keyword arguments for customization
- Validate password strength with checks
- Generate multiple passwords at once
Prerequisites
- Functions and parameters
- String methods
- Importing modules
Steps
- 1
Write the generator function
Import random and string. Define generate_password(length, use_symbols) that builds a character set and randomly selects from it.
Codeimport random import string def generate_password(length=12, use_symbols=True): chars = string.ascii_letters + string.digits if use_symbols: chars += string.punctuation password = ''.join(random.choice(chars) for _ in range(length)) return passwordExpected result
generate_password() returns a random 12-character password with symbols.
- 2
Add strength checking
Define check_strength(password) that returns 'weak', 'medium', or 'strong' based on length and character variety.
Codedef check_strength(password): has_upper = any(c.isupper() for c in password) has_lower = any(c.islower() for c in password) has_digit = any(c.isdigit() for c in password) has_symbol = any(c in string.punctuation for c in password) variety = sum([has_upper, has_lower, has_digit, has_symbol]) if len(password) >= 12 and variety >= 4: return "strong" elif len(password) >= 8 and variety >= 3: return "medium" else: return "weak"Expected result
check_strength('Abc123!@#xyz') returns 'strong'.
- 3
Generate and display passwords
Generate 5 passwords of different lengths, check each one's strength, and print them in a formatted table.
Codeprint(f"{'#':<4} {'Password':<20} {'Strength':<10}") print('-' * 34) for i in range(1, 6): length = 8 + i * 2 pwd = generate_password(length=length) strength = check_strength(pwd) print(f"{i:<4} {pwd:<20} {strength:<10}")Expected result
A table of 5 passwords with varying lengths and their strength ratings.
- 4
Add input validation & exception handling
Add a try/except block in the main function to handle user input errors, using ValueError to catch illegal conversions. Python's exception handling lets the program degrade gracefully on bad input instead of crashing.
Codedef safe_input(prompt, validator=None): """Read input with validation and error handling.""" while True: try: raw = input(prompt) value = float(raw) if validator and not validator(value): raise ValueError(f"Value {value} failed validation") return value except ValueError as err: print(f"Invalid input: {err}. Please try again.") # Usage age = safe_input("Enter your age: ", lambda x: x > 0)Expected result
Invalid input (non-number or failed validation) prompts for re-entry; valid input returns the number.
- 5
Write unit tests
Write tests for the core function using unittest or assert statements, covering normal paths, boundary values, and exceptions. Tests are the safety net for code quality.
Codeimport unittest class TestCoreFunc(unittest.TestCase): def test_normal(self): self.assertEqual(core_func(5), expected_5) def test_boundary(self): self.assertEqual(core_func(0), expected_0) def test_exception(self): with self.assertRaises(ValueError): core_func(-1) if __name__ == "__main__": unittest.main()Expected result
Running python test.py prints OK with all three test cases passing.
Try it yourself
import random
import string
# TODO: define generate_password and check_strength
# Then generate and display 5 passwords
import random
import string
def generate_password(length=12, use_symbols=True):
chars = string.ascii_letters + string.digits
if use_symbols:
chars += string.punctuation
password = ''.join(random.choice(chars) for _ in range(length))
return password
def check_strength(password):
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)
has_symbol = any(c in string.punctuation for c in password)
variety = sum([has_upper, has_lower, has_digit, has_symbol])
if len(password) >= 12 and variety >= 4:
return "strong"
elif len(password) >= 8 and variety >= 3:
return "medium"
else:
return "weak"
print(f"{'#':<4} {'Password':<20} {'Strength':<10}")
print('-' * 34)
for i in range(1, 6):
length = 8 + i * 2
pwd = generate_password(length=length)
strength = check_strength(pwd)
print(f"{i:<4} {pwd:<20} {strength:<10}")What you learned
You combined the random and string modules, built configurable functions, and implemented strength checking — the same logic behind real password tools.
Related Resources
Related Lessons
- Python Functions
Functions with defaults.
- Strings
String module constants.
Related Practice
- Default Argument Quiz
Default arguments.
- Predict Function Output
Function behavior.
Related Tools
- Password Generator
Compare with the browser tool.
Related Cheatsheets
- Python Cheatsheet
random and string reference.
Related Errors
- Type Error
Type issues.
- Value Error
Invalid length values.
Related Glossary
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Related Errors
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
- Type Error
Type issues.
- Value Error
Invalid length values.