Day 7 · Day 7: Intermediate Python
Password Generator
Build a secure password generator that creates random passwords based on user-specified length and character sets, using list comprehensions, the random module, and string constants.
Requirements
1. Ask the user for the desired password length.
2. Ask the user which character types to include: lowercase, uppercase, digits, symbols.
3. Use Python's string module constants (string.ascii_lowercase, string.ascii_uppercase, string.digits, string.punctuation).
4. Combine selected character sets into a single pool using a list comprehension or string concatenation.
5. Use random.choice() in a loop or comprehension to generate the password.
6. Validate that at least one character type is selected and length is reasonable (e.g., >= 4).
7. Allow generating multiple passwords without restarting the program.
2. Ask the user which character types to include: lowercase, uppercase, digits, symbols.
3. Use Python's string module constants (string.ascii_lowercase, string.ascii_uppercase, string.digits, string.punctuation).
4. Combine selected character sets into a single pool using a list comprehension or string concatenation.
5. Use random.choice() in a loop or comprehension to generate the password.
6. Validate that at least one character type is selected and length is reasonable (e.g., >= 4).
7. Allow generating multiple passwords without restarting the program.
import random
import string
def generate_password(length, use_lower, use_upper, use_digits, use_symbols):
pool = ""
if use_lower:
pool += string.ascii_lowercase
if use_upper:
pool += string.ascii_uppercase
if use_digits:
pool += string.digits
if use_symbols:
pool += string.punctuation
if not pool:
raise ValueError("At least one character type must be selected.")
password = "".join(random.choice(pool) for _ in range(length))
return password
def ask_yes_no(prompt):
return input(prompt).strip().lower() in ("y", "yes")
def main():
while True:
try:
length = int(input("Password length (min 4): "))
if length < 4:
print("Length must be at least 4.")
continue
except ValueError:
print("Please enter a valid number.")
continue
use_lower = ask_yes_no("Include lowercase letters? (y/n): ")
use_upper = ask_yes_no("Include uppercase letters? (y/n): ")
use_digits = ask_yes_no("Include digits? (y/n): ")
use_symbols = ask_yes_no("Include symbols? (y/n): ")
try:
password = generate_password(length, use_lower, use_upper, use_digits, use_symbols)
print(f"\nGenerated Password: {password}\n")
except ValueError as e:
print(f"Error: {e}")
continue
if not ask_yes_no("Generate another password? (y/n): "):
print("Goodbye!")
break
if __name__ == "__main__":
main()
50 XP on completion
Back to Day 7
Your Code
Output
Click "Run" to execute your code...
⏳ Loading Python runtime (first run may take a few seconds)...
Log in to mark this project complete and earn XP.