Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
Mini Project: Password Generator
Build a Python password generator! This mini project combines functions, string operations, and the random module to create secure, customizable passwords.
Password Generator
import random
import string
def generate_password(length=12, use_upper=True, use_digits=True, use_special=True):
"""Generate a random password with customizable options."""
# Build character pool
chars = string.ascii_lowercase # a-z
if use_upper:
chars += string.ascii_uppercase # A-Z
if use_digits:
chars += string.digits # 0-9
if use_special:
chars += "!@#$%^&*()_+-="
# Generate password
password = ''.join(random.choice(chars) for _ in range(length))
return password
def check_strength(password):
"""Check password strength."""
score = 0
if len(password) >= 8: score += 1
if len(password) >= 12: score += 1
if any(c.isupper() for c in password): score += 1
if any(c.isdigit() for c in password): score += 1
if any(c in "!@#$%^&*()_+-=" for c in password): score += 1
levels = {0: "Very Weak", 1: "Weak", 2: "Fair", 3: "Good", 4: "Strong", 5: "Very Strong"}
return levels.get(score, "Unknown")
# Generate passwords
print("=== Password Generator ===\n")
for i in range(5):
pwd = generate_password(length=16)
strength = check_strength(pwd)
print(f"Password {i+1}: {pwd} [{strength}]")
# Custom options
print("\n--- Short pin ---")
print(generate_password(length=4, use_upper=False, use_special=False))
print("\n--- Letters only ---")
print(generate_password(length=10, use_digits=False, use_special=False))Try It Yourself: Customize the Generator
Tip
Tip
Use string.ascii_letters + string.digits for character pools. The secrets module is more secure than random for password generation.
Functions are first-class objects in Python - pass them, return them, store them
Common Mistake
Warning
Using random for security-sensitive code. random is predictable. Use secrets.choice() for cryptographic randomness in real password generators.
Practice Task
Note
(1) Generate 5 passwords of different lengths. (2) Add a strength checker. (3) Ensure at least one uppercase, one digit, one special character.