Files
python-flask/project07/[任务书]验证码生成系统.md
2025-09-11 16:52:33 +08:00

60 lines
1.4 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 验证码生成系统
## 需求
- 编写函数生成随机6位验证码要求验证码的组成有0-9, a-z, A-Z
## 参考代码
```python
import random
def random_char_generator():
# 生成可以用作验证码字符的列表
word = []
# 将0-9的字符串都加入这个列表中
for i in range(10):
word.append(str(i))
# 将a-z都加入这个列表中
# 原理是取ascii码表中的97-122然后转换为字符存入列表
for i in range(97,123):
word.append(chr(i))
# 将A-Z都加入这个列表中
for i in range(65, 91):
word.append(chr(i))
# 生成器,用于从列表中随机获取内容
while True:
yield random.choice(word)
def generate_verification_code(length):
"""生成指定长度的验证码"""
if length < 1:
raise ValueError("验证码长度至少为1")
# 创建一个生成器对象
gen = random_char_generator()
verification_code = ""
for i in range(length):
# 使用生成器生成验证码,将每次生成的随机字符+到之前产生的字符后面
verification_code += next(gen)
return verification_code
# 生成一个6位验证码
print(generate_verification_code(6))
```
><span style="color: red; background: yellow; padding: 2px 5px; font-size: 22px;">作业7.1提交的内容</span>
>
>- 理解程序的运行逻辑
>- 程序运行成功的截图,单独发送给组长