Python凯撒密码程序报错:NameError: name 'shift_amount' is not defined
凯撒密码编码解码应用修复方案
问题概述
编写学校作业的凯撒密码应用,要求以小写字母作为移位键实现消息编码解码,当前遇到报错:
NameError: name 'shift_amount' is not defined
同时编码逻辑未完善,代码末尾输出存在问题,核心需求是修复encode/decode方法内的代码问题。
原始代码
lower_case=['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'] upper_case=['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'] class CaesarCipher: def encode(text, shift_key): print(f"encode message {text} with {shift_key}") encoded_msg=text num=shift_amount(shift_key) #find the test letter #print the index for this number #add the num to that index #print the new letter for chr in text: if chr.islower(): shifted_chr = CaesarCipher.lower_case[(CaesarCipher.lower_case.index(chr) + shift) % 26] encoded_msg += shifted_chr else: encoded_msg += chr return encoded_msg def decode(text, shift_key): print(f"decode message {text} with {shift_key}") decoded_msg=text num=shift_amount(shift_key) for chr in text: if chr.islower(): shifted_chr = CaesarCipher.lower_case[(CaesarCipher.lower_case.index(chr) - shift) % 26] decoded_msg += shifted_chr else: decoded_msg += chr return decoded_msg def shift_amount(shift_key): #do something (how many shifts?) #a=0,b=1,z=25 matching_index = -1 count=0 if shift_key in lower_case: print("it's valid") while count < len(lower_case): if shift_key == lower_case [count]: matching_index = count print(f"found matching index: {lower_case[count]}") return matching_index else: print("it's failed") count +=1 else: print("Invalid") encode("hello","b") decode("hello","b") shift_key=input("choose a shift amount ") num=shift_amount(shift_key) print(f"Number is {str(num)}")
核心修复点
1. 类方法调用与定义修正
- 类内方法需添加
self参数或定义为静态方法,否则无法正确调用类内其他方法;这里用@staticmethod标记所有方法,无需实例化即可调用。 - 调用类内
shift_amount方法时,必须用CaesarCipher.shift_amount(),直接写shift_amount()会因找不到全局函数报错。
2. 变量未定义问题修复
encode/decode方法中使用的shift变量未定义,需替换为实际获取的移位量num。encoded_msg/decoded_msg初始值设为原文本会导致结果重复拼接,改为初始化为空字符串""。
3. 类访问外部变量问题修正
lower_case是全局变量,类内无需通过CaesarCipher.lower_case访问,直接使用全局变量即可。
4. shift_amount方法优化
- 用
lower_case.index(shift_key)替代循环查找,简化逻辑;同时增加无效输入的返回值,避免后续计算出错。
5. 类内方法调用位置调整
- 类定义阶段不能直接调用
encode/decode,需放到类定义完成后执行。
修复后完整代码
lower_case = ['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'] upper_case = ['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'] class CaesarCipher: @staticmethod def encode(text, shift_key): print(f"编码消息: {text},移位键: {shift_key}") encoded_msg = "" num = CaesarCipher.shift_amount(shift_key) if num == -1: print("无效的移位键,请输入小写字母") return text for char in text: if char.islower(): original_idx = lower_case.index(char) new_idx = (original_idx + num) % 26 shifted_char = lower_case[new_idx] encoded_msg += shifted_char elif char.isupper(): original_idx = upper_case.index(char) new_idx = (original_idx + num) % 26 shifted_char = upper_case[new_idx] encoded_msg += shifted_char else: encoded_msg += char return encoded_msg @staticmethod def decode(text, shift_key): print(f"解码消息: {text},移位键: {shift_key}") decoded_msg = "" num = CaesarCipher.shift_amount(shift_key) if num == -1: print("无效的移位键,请输入小写字母") return text for char in text: if char.islower(): original_idx = lower_case.index(char) new_idx = (original_idx - num) % 26 shifted_char = lower_case[new_idx] decoded_msg += shifted_char elif char.isupper(): original_idx = upper_case.index(char) new_idx = (original_idx - num) % 26 shifted_char = upper_case[new_idx] decoded_msg += shifted_char else: decoded_msg += char return decoded_msg @staticmethod def shift_amount(shift_key): # 小写字母对应移位量:a=0, b=1...z=25 if shift_key in lower_case: return lower_case.index(shift_key) else: print("无效的移位键,必须是小写字母") return -1 # 测试编码解码 encoded_result = CaesarCipher.encode("hello", "b") print(f"编码结果: {encoded_result}") decoded_result = CaesarCipher.decode(encoded_result, "b") print(f"解码结果: {decoded_result}") # 用户交互部分 shift_key = input("请选择一个小写字母作为移位键: ") num = CaesarCipher.shift_amount(shift_key) if num != -1: print(f"对应的移位量是: {num}")
额外优化说明
- 新增大写字母的编码解码逻辑,完善功能覆盖范围。
- 增加无效输入的提示与处理,提升程序健壮性。
- 简化
shift_amount方法实现,提升代码效率与可读性。
内容的提问来源于stack exchange,提问作者Flo
相关产品推荐
相关产品推荐

