T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 5 天:循环与列表

这是「Python 100 天」系列第 5 天的学习笔记:循环与列表:密码生成器。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

按用户要求的"字母数 / 符号数 / 数字数"随机抽取字符,拼成密码并打乱,最后给一个强度评价。README 知识点:for 循环遍历列表、range()。

一、for 循环

Python 的 for 是"遍历可迭代对象",不是 C++ 那种"三段式计数循环":

1
2
3
4
5
for ch in "abc":
print(ch) # a b c

for n in [10, 20, 30]:
print(n)

要计数循环就用 range():

1
2
3
4
range(5)         # 0,1,2,3,4
range(2, 5) # 2,3,4
range(0, 10, 2) # 0,2,4,6,8 第三个参数是步长
range(5, 0, -1) # 5,4,3,2,1

range 是左闭右开:range(0, 52) 给 0~51,刚好对应 52 个字母的下标。

for i in range(5): 里如果不需要 i,按惯例写成 for _ in range(5):(下划线表示"不用的变量")。

二、列表的追加与打乱

1
2
3
4
password = []
password.append("a") # 末尾追加
random.shuffle(password) # 原地打乱,返回 None
"".join(password) # 用空串把字符连起来

"".join(list) 是列表转字符串的标准做法。str(list) 会得到 "['a', 'b']" 这种带方括号和引号的东西,不是你要的。

三、三个字符池

作者手写了字母表(大小写各 26 个,共 52 个)、10 个数字、9 个符号。也可以写成:

1
2
3
4
import string
letters = string.ascii_letters # 大小写字母
digits = string.digits
symbols = string.punctuation

代码全文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# ============================================================
# day05/main.py —— 密码生成器(PyPassword Generator)
# 作用:按用户指定的字母/数字/符号数量,随机取字符拼成一个密码,并评估强度。
# 知识点:random.randint()、random.shuffle()、list.append()、str.join()、str.isdigit()、len()
# 运行:python main.py
# ============================================================

# 导入标准库 random,后面要用 randint 和 shuffle。
import random

# 三个列表就是“字符表”,放在列表里是为了能用下标随机取:
# 列表下标从 0 开始,letters[0] 是 'a',letters[25] 是 'z',letters[26] 是 'A' …
# 小写 26 个 + 大写 26 个 = 52 个字母,所以后面取随机下标时用 randint(0, 51)。
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# 10 个数字字符(注意是字符串 '0',不是整数 0),下标范围 0–9。
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
# 9 个符号,下标范围 0–8。
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']

print("Welcome to the PyPassword Generator!")
nr_letters= (input("How many letters would you like in your password?n"))
# 这里多写了个 f 前缀但字符串里没有 {},f 不起作用,属于无害的冗余。
nr_symbols = (input(f"How many symbols would you like?n"))
nr_numbers = (input(f"How many numbers would you like?n"))

# str.isdigit():判断字符串是否全为数字字符,返回 True/False。
# not A or not B or not C:任何一个不是数字,就整体为真 → 走错误分支。
# 用 or 而不是 and,是因为“只要有一个非法”就该报错。
if not nr_letters.isdigit() or not nr_symbols.isdigit() or not nr_numbers.isdigit():
print("Invalid value, enter a number instead.")
else:
# 用一个空列表当“容器”,后面把字符一个个 append 进去,顺序先不管,最后再打乱。
password = []

# random.randint(0, 51):返回 0–51(含两端)的随机整数,正好是 letters 的合法下标。
# 这一行其实是多余的(下面循环里第一句又取了一次),不影响结果,只是多调用一次。
random_letter = random.randint(0, 51)

# range(0, n):生成 0,1,…,n-1 的整数序列(不含右端),常用于“重复 n 次”。
# int(nr_letters):input 得到的是字符串,range 只接受整数,必须先转。
for i in range(0, int(nr_letters)):
random_letter = random.randint(0, 51)
# list.append(x):列表方法,把 x 加到列表末尾。
# 参数 x:任意对象;返回值:None(它是原地修改列表,不产生新列表)。
password.append(letters[random_letter])

# 数字部分:取 randint(0,9) 当下标,从 numbers 里取一个字符。
random_number = random.randint(0,9)
for i in range(0, int(nr_numbers)):
random_number = random.randint(0,9)
password.append(numbers[random_number])

# 符号部分:取 randint(0,8) 当下标(symbols 只有 9 个元素)。
random_symbol = random.randint(0,8)
for i in range(0, int(nr_symbols)):
random_symbol = random.randint(0,8)
password.append(symbols[random_symbol])

# random.shuffle(x)
# 模块函数,把列表 x **原地**随机打乱顺序。
# 参数 x:可变序列(通常是 list);返回值:None(原地修改,不打乱副本)。
# 为什么要打乱?因为上面是“先所有字母、再所有数字、再所有符号”,
# 不打乱的话密码结构固定,安全性会变差。
random.shuffle(password)

# ''.join(可迭代对象)
# 字符串方法,用一个空串当“胶水”,把列表里的字符串依次粘起来。
# 参数:可迭代对象,元素必须全是 str;
# 返回值:一个新的 str,例如 ['a','b'] → "ab"。
# 注意 join 是字符串的方法,不是列表的:写法永远是 分隔符.join(列表)。
print(f"Here is your password: {''.join(password)}")

# len(x):内置函数,返回 x 的长度(字符串是字符数,列表是元素个数)。
# 返回值为 int。用它来判断密码强度。
if len(password) <= 6:
print("Your password is weak, try to include at least 8 characters for a stronger password.")
elif len(password) == 7:
print("Your password is medium, try to include at least 8 characters for a stronger password.")
else:
print("Your password is strong.")

代码走读

  1. 三个输入先拿到字符串,用 isdigit() 统一校验,避免后面 int() 崩掉。
  2. 每类字符各用一个 for 循环:
1
2
3
for i in range(0, int(nr_letters)):
random_letter = random.randint(0, 51)
password.append(letters[random_letter])

循环次数是用户要的字母个数,每次在 0~51 里取一个下标,从 letters 里取出字符追加进 password。

  1. random.shuffle(password) 打乱顺序——如果不打乱,密码就是"字母全在前、数字居中、符号在后",规律性太强。这是本项目的关键一步。
  2. ''.join(password) 拼成字符串输出。
  3. 最后按 len(password) 分三档评价强度。

可以简化的地方

循环体里其实可以一行搞定:

1
password.append(random.choice(letters))

random.choice 直接从序列里挑一个,不需要自己算下标,也就不需要知道"字母有 52 个"这个魔法数字。还有更 Python 的写法是列表推导式(Day 26 讲):

1
password += [random.choice(letters) for _ in range(int(nr_letters))]

运行示例

1
2
3
4
5
6
7
8
9
Welcome to the PyPassword Generator!
How many letters would you like in your password?
5
How many symbols would you like?
2
How many numbers would you like?
2
Here is your password: $k7Qa!2mXe
Your password is strong.

易错点

  1. range(int(nr_letters)) 漏了 int:range("5") 报 TypeError。
  2. shuffle 赋值:password = random.shuffle(password) 会把 password 变成 None,因为 shuffle 原地操作、返回 None。
  3. random.randint(0, 51) 写成 (0, 52):偶尔会 IndexError,因为下标最大只到 51。
  4. 强度判断只看长度:这是产品逻辑的简化,真实强度还要看字符集大小。

动手改

  • 用 random.choice 重写三个循环。
  • 加"必须至少包含 1 个数字和 1 个符号"的校验,不满足就重新生成。
  • 把魔法数字 51、9 换成 len(letters) - 1,让代码不再依赖硬编码。

源文件逐个讲解

2 个文件:main.py(42 行)、README.md(9 行)。

main.py(42 行)

结构:3 个字符池 + 3 个数量输入 + 3 段追加循环 + 洗牌

1
2
3
letters = ['a', 'b', ..., 'z', 'A', 'B', ..., 'Z']   # 26 小写 + 26 大写 = 52 个
numbers = ['0', ..., '9'] # 10 个
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] # 9 个

全是字符串列表,不是字符。所以后面拼密码得用 ''.join(password),不能直接 +。

1
2
3
4
5
6
nr_letters= (input("How many letters would you like in your password?n"))
nr_symbols = (input(f"How many symbols would you like?n"))
nr_numbers = (input(f"How many numbers would you like?n"))

if not nr_letters.isdigit() or not nr_symbols.isdigit() or not nr_numbers.isdigit():
print("Invalid value, enter a number instead.")

三个输入都是字符串,靠 isdigit() 一次性校验。or 短路:任意一个不是数字就整体报错。注意这里的 f"..." 没有插值,写 f 是多余的。

三段几乎一样的循环:

1
2
3
4
random_letter = random.randint(0, 51)      # ← 这行赋值后没被用过
for i in range(0, int(nr_letters)):
random_letter = random.randint(0, 51)
password.append(letters[random_letter])

randint(0, 51) 对应 letters 的 52 个元素,randint(0, 9) 对应 numbers,randint(0, 8) 对应 symbols——三个魔法数字都是硬编码的长度。往 symbols 里加一个符号,这里就会 IndexError。正确写法 random.choice(letters),长度自动适应。

三段循环的第一行都有一句「进循环前先随机一次」的赋值,完全没用(循环里立刻被覆盖)。这是典型的复制粘贴残留。

洗牌与强度判断:

1
2
3
4
5
6
7
8
9
random.shuffle(password)
print(f"Here is your password: {''.join(password)}")

if len(password) <= 6:
print("Your password is weak, ...")
elif len(password) == 7:
print("Your password is medium, ...")
else:
print("Your password is strong.")

shuffle 原地打乱且返回 None,所以不能写 password = random.shuffle(password)。

强度规则只看总长度,不看字符种类——但既然密码里必然混了三类字符,长度确实是主要因素。<=6 弱、==7 中、>=8 强,这个阈值是作者自己定的,不是任何标准。

这份代码的问题

  1. 魔法数字 51 / 9 / 8:池子一变就崩。
  2. 三段时间复杂度都是 O(n),但代码重复三遍,可以合成一个 for pool, count in [(letters, n1), ...]。
  3. isdigit() 允许 "0":要 0 个字母、0 个符号、0 个数字,会生成空密码然后打印「Your password is strong」。
  4. int(nr_letters) 转换了四次(校验一次、循环一次),可以一开始就转好。

README.md(9 行)

标题 Day 5 - Python Loops,知识点是 Using the for loop with Python Lists、for loops and the range() function。和代码完全对应:三个 for + range 就是当天全部内容。

文件间关系

单文件,依赖 random。这一天还没学函数,所以逻辑全是「平铺」的——Day 10 之后同样的程序会被拆成函数。

微信收款码 微信
支付宝收款码 支付宝
评论