密码 Generator
你将构建什么
Python script 那个 generates random 密码使用 configurable 长度, character 类型 (letters, digits, symbols), and strength 检查.
学习目标
- Use random and 字符串模块 for character selection
- 构建函数使用 keyword 实参 for customization
- 验证密码 strength 使用检查
- Generate 多个密码 at 一次
前置要求
- 函数 and 参数
- 字符串方法
- Importing 模块
步骤
- 1
编写 generator 函数
导入 random and 字符串. 定义 generate_password(长度, use_symbols) 那个构建 character 设置 and randomly 选择从 它.
代码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预期结果
generate_password() 返回 random 12-character 密码使用 symbols.
- 2
添加 strength 检查
定义 check_strength(密码) 那个返回 'weak', '中等', or 'strong' based on 长度 and character variety.
代码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"预期结果
check_strength('Abc123!@#xyz') 返回 'strong'.
- 3
Generate and display 密码
Generate 5 密码的 不同长度, 检查每个 one's strength, and print 它们 in 格式化表.
代码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}")预期结果
表的 5 密码使用 varying 长度 and 它们的 strength ratings.
- 4
添加输入验证与异常处理
在主函数中添加 try/except 块处理用户输入错误,使用 ValueError 捕获非法转换。Python 的异常处理让程序对错误输入优雅降级而非崩溃。
代码def 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)预期结果
非法输入(非数字或验证失败)提示重新输入;合法输入返回数值。
- 5
编写单元测试
使用 unittest 或 assert 语句为核心函数编写测试,覆盖正常路径、边界值和异常情况。测试是保证代码质量的安全网。
代码import 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()预期结果
运行 python test.py 后输出 OK,三个测试用例全部通过。
自己动手试试
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}")你学到了什么
你组合 random and 字符串模块, 构建 configurable 函数, and implemented strength 检查 — 相同 logic 后面真实密码 tools.
相关资源
相关练习
- 默认实参测验
默认实参.
- Predict 函数输出
函数 behavior.
相关工具
- 密码 Generator
Compare 使用浏览器 tool.
相关速查表
- Python Cheatsheet
random and 字符串引用.
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
相关错误
用大白话解释常见错误——什么意思、为什么发生、如何修复。