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

Python 100 天 · 第 8 天:函数参数:凯撒密码

这是「Python 100 天」系列第 8 天的学习笔记:函数参数:凯撒密码。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

把一句话按固定位数平移字母(加密),或反向平移(解密)。README 知识点:带输入参数的函数、位置参数与关键字参数。

一、带参数的函数

1
2
3
4
5
def greet(name, greeting):
print(f"{greeting}, {name}!")

greet("Tom", "Hello") # 位置参数:按顺序对应
greet(greeting="Hi", name="Tom") # 关键字参数:按名字对应,顺序随意

规则:

  • 位置参数必须在关键字参数之前;
  • 参数可以有默认值 def f(a, b=2),有默认值的必须放在后面;
  • 调用时参数个数不匹配会 TypeError。

二、凯撒密码的数学

字母表 26 个字母,平移 shift 位:新下标 = (旧下标 + shift) % 26。

取模保证"越过 z 回到 a"。作者用了另一种等价做法:把字母表复制两遍,长度 52。

1
2
3
4
alphabet = ['a', ..., 'z', 'a', ..., 'z']
position = alphabet.index('y') # 24
new_position = 24 + 3 # 27
alphabet[27] # 'b'

这样 x/y/z 往后移不会越界,代价是字母表要写两遍、shift 不能超过 26(超过就会越界)。

三、.index() 与 .isalpha()

1
2
3
4
alphabet.index('c')     # 2,找不到会抛 ValueError
"a".isalpha() # True
"1".isalpha() # False
" ".isalpha() # False

isalpha() 用来区分"字母"和"空格、标点、数字"——非字母原样保留,这样句子结构不会被破坏。

代码全文

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
# ============================================================
# day08/main.py —— 凯撒密码(Caesar Cipher)
# 作用:把一句话按用户给的数字整体位移加密(encode)或还原解密(decode)。
# 知识点:def 带参数的函数、字符串方法 isalpha()/index()、取余 %、
# 函数的关键字调用、while 主循环
# 运行:python main.py
# ============================================================

# 从 art.py 里导入 logo(一段 ASCII 图案字符串)。
from art import logo

# alphabet 是“字母表索引”:正常 a–z 各一个,后面又重复了一遍 a–z。
# 为什么要重复?加密时 z 往后移 1 位会越界,重复一遍后 alphabet[25+1] 正好回到 'a',
# 省掉了自己写取余的麻烦。代价是:位移量必须 ≤ 25,否则仍会越界。
alphabet = ['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']

# def 函数名(参数1, 参数2, 参数3): —— 定义函数。
# start_text :要处理的原文(str)
# shift_amount :位移量(int),例如 3 表示每个字母往后挪 3 位
# cipher_direction:方向(str),"encode" 加密 / "decode" 解密
# 返回值:无(函数内部直接 print 结果)。想更规范的话应该 return end_text,
# 让“计算”和“显示”分开——Day10 的 calculator 就是这么做的。
def caesar(start_text, shift_amount, cipher_direction):
# 用一个空串收集结果,边循环边往后面拼。
end_text = ""
# 解密 = 反向位移。把位移量取负,后面就只用一套“往后挪”的逻辑。
if cipher_direction == "decode":
shift_amount *= -1
# for 变量 in 字符串:逐个取字符,char 依次是第一个字母、第二个字母……
for char in start_text:
# str.isalpha()
# 字符串方法,无参数。判断这个字符是不是字母(a–z / A–Z,含非英文字母),返回 True/False。
# 为什么先判断?因为空格、标点、数字没有“位移 3 位”的概念,必须原样保留。
if char.isalpha():
# str.index(sub)
# 字符串方法。参数 sub 是要找的子串,返回它第一次出现的下标(从 0 开始);
# 找不到会抛 ValueError。
# 这里用它在 alphabet 里定位当前字母的位置。
position = alphabet.index(char)
# 目标下标 = 原下标 + 位移量(解密时 shift 已经是负数)
new_position = position + shift_amount
# 取新字母拼到结果后面;+= 对字符串就是“拼接并重新赋值”。
end_text += alphabet[new_position]
else:
# 非字母(空格、逗号、数字)原样拼回去。
end_text += char
# f-string 里 {cipher_direction}d 会变成 "encoded" / "decoded"(把动词和 d 拼一起)
print(f"Here's the {cipher_direction}d result: {end_text}n")

# 主循环:run 为 True 就一直重复“输入 → 加密 → 问要不要继续”。
run = True
while run:
print(logo)
# direction 后面会作为关键字实参传进 caesar()
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:n")
# 原文统一转小写,才能和 alphabet 里的小写字母对上。
text = input("Type your message:n").lower()
# int():把字符串转整数,因为位移量要参与数学运算。
shift = int(input("Type the shift number:n"))

# 作者想处理“位移超过 26”的情况,但这一行写错了:
# shift % shift 恒等于 0(任何非零数除以自己余 0),
# 所以 "shift = shift % shift == 0" 实际是 shift = True(布尔值),
# 接下去 alphabet[position + True] 只是多挪了 1 位,并不是“对 26 取余”。
# 正确写法:shift = shift % 26
if shift > 26:
shift = shift % shift == 0

# 关键字调用:按“参数名=值”的方式传参,顺序可以打乱,
# 也不会因为参数位置记错而传反——参数多的时候强烈建议这样写。
caesar(start_text=text, shift_amount=shift, cipher_direction=direction)
choice = input("Do you want to run this program again?nType 'yes' or 'no': ")
if choice == 'no':
# 把循环条件改成 False,while 下一轮就会退出。
run = False
print("Goodbye.")

代码走读

  1. def caesar(start_text, shift_amount, cipher_direction): 三个参数分别是要处理的文本、平移量、方向。
  2. if cipher_direction == "decode": shift_amount *= -1——解密就是反向平移,把正数变负数,后面逻辑完全复用。
  3. for char in start_text: 逐字符处理。
  4. 字母分支:position = alphabet.index(char) 找到下标,加上偏移,再取新字符,end_text += ... 累积结果。
  5. 非字母分支:end_text += char 原样保留空格和标点。
  6. 主循环里读输入、调用函数,然后问"是否继续",用 run 标志控制。

这份代码里的两个真问题

(1) 平移量处理写错了

1
2
if shift > 26:
shift = shift % shift == 0

shift % shift 永远是 0,0 == 0 是 True,所以这里把 shift 变成了布尔值 True(在运算中等价于 1)。想表达"超过 26 就取余",正确写法是:

1
shift = shift % 26

(2) 大小写与负数

text 被 .lower() 统一成小写,所以大写字母永远无法还原;如果 shift 是负数且绝对值很大,new_position 可能为负,alphabet[-3] 会从末尾取,结果错但不报错——这种"不报错的错"最难查。

运行示例

1
2
3
4
5
6
7
Type 'encode' to encrypt, type 'decode' to decrypt:
encode
Type your message:
hello world
Type the shift number:
3
Here's the encoded result: khoor zruog

易错点

  1. alphabet.index(char) 对非字母抛 ValueError:所以必须先 isalpha() 判断。
  2. 忘记 % 26 或双字母表:z 往后移会越界。
  3. shift 是字符串:int(input()) 不能省。
  4. 大小写被 lower() 吃掉:需要保留大小写时,应判断 char.isupper() 后分别处理。

动手改

  • 改成标准取模写法:alphabet = list("abcdefghijklmnopqrstuvwxyz") + (position + shift) % 26。
  • 保留大小写:大写字母在大写字母表里平移。
  • 支持中文/emoji 混排:非 ASCII 字符原样输出。

源文件逐个讲解

3 个文件:main.py(34 行)、art.py(9 行)、README.md(7 行)。

art.py(9 行)

1
2
3
4
5
logo = """           
,adPPYba, ,adPPYYba, ,adPPYba, ,adPPYba, ,adPPYYba, ,adPPYba,
a8" "" "" `Y8 a8" "" "" "" "" `Y8 a8" "8a
...
"""

只有一个变量 logo,是一幅 6 行的 ASCII 字「CAESAR」。注意第一行 """ 后面跟了一串空格——那是为了让字符画在源码里对齐,输出时这些空格会原样出现在终端最左边。

main.py(34 行)

结构:字母表 → 加密函数 → 主循环

1
2
3
from art import logo

alphabet = ['a', 'b', ..., 'z', 'a', 'b', ..., 'z']

字母表刻意写了 52 个元素(a–z 重复两遍),这样 position + shift 最多到 25+25=50,不会越界——用「复制一份字母表」代替取模。这是新手最常见的绕坑方式,代价是 shift 超过 26 就崩(下面会看到它试图修这个问题,但修错了)。

1
2
3
4
5
6
7
8
9
10
11
12
def caesar(start_text, shift_amount, cipher_direction):
end_text = ""
if cipher_direction == "decode":
shift_amount *= -1
for char in start_text:
if char.isalpha():
position = alphabet.index(char)
new_position = position + shift_amount
end_text += alphabet[new_position]
else:
end_text += char
print(f"Here's the {cipher_direction}d result: {end_text}n")

四个要点:

  1. 解码就是负向位移:shift_amount *= -1,一套代码同时处理加密和解密。
  2. char.isalpha() 过滤空格和标点,非字母原样保留。isalpha() 对中文也返回 True,但中文不在 alphabet 里,会 ValueError——这份代码只处理英文。
  3. end_text += char 字符串拼接在循环里,字符多时是 O(n²)(每次都要新建字符串)。教学代码无所谓,真实场景用列表 append 再 join。
  4. 没处理大写:alphabet 里只有小写,但主循环里 text = input(...).lower() 兜住了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
run = True
while run:
print(logo)
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:n")
text = input("Type your message:n").lower()
shift = int(input("Type the shift number:n"))

if shift > 26:
shift = shift % shift == 0

caesar(start_text=text, shift_amount=shift, cipher_direction=direction)
choice = input("Do you want to run this program again?nType 'yes' or 'no': ")
if choice == 'no':
run = False
print("Goodbye.")

shift = shift % shift == 0 这一行是整份代码最严重的 bug。

Python 里 % 和 == 的优先级是:== 比 % 低,所以这行等价于:

1
shift = (shift % shift) == 0      # shift % shift 恒为 0,所以恒为 True

结果 shift 变成了布尔值 True,传进函数后 position + True 等于 position + 1——所有超过 26 的位移都变成了「右移 1 位」。

想表达的是「超过 26 就绕回来」,正确写法:

1
shift = shift % 26

还有一个连锁问题:True 参与 alphabet[new_position] 时,如果 position 是 25,25 + 1 = 26 正好是第二个 'a',不越界;但如果 shift 原本是 30,期望移 4 位,实际只移了 1 位——结果错但不报错,这种 bug 最难发现。

这份代码的问题

  1. shift = shift % shift == 0(见上,最严重)。
  2. direction 没校验:输入 "ENCODE"(大写)不会进 if cipher_direction == "decode",被当成加密处理——碰巧是对的;输入 "foo" 也会走加密分支,打印 "Here's the food result"。
  3. 负数位移:shift = -3 时 position - 3 可能是负的,Python 的负索引会从末尾取值,不报错但结果错。
  4. alphabet.index() 是 O(n),52 个元素无所谓,但概念上应该用字典建映射。
  5. end_text += char 的 O(n²)。

README.md(7 行)

标题 Day 8 - Function Parameters & Caesar Cipher,知识点是 Functions with Inputs、Positional vs. Keyword Arguments。

代码里同时演示了两种传参:函数定义用位置参数 (start_text, shift_amount, cipher_direction),调用时用关键字 caesar(start_text=text, ...)。这就是当天的主旨。

文件间关系

main.py 只从 art.py 拿一个 logo。art.py 是纯粹的「素材文件」——没有函数、没有逻辑,改字符画不影响程序行为。这种拆分在 Day 09–14 会重复出现(每天一个 art.py)。

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