Python中如何编写正确if语句实现凯撒密码输入校验
最小改动实现凯撒密码程序的输入合法性校验
不需要重构现有代码,仅在获取功能选择的节点补充少量判断逻辑,即可实现非法输入时提示重试的需求,原有代码的整体执行流程、函数实现完全不做改动。
改动思路
- 校验节点选在读取用户功能选择输入之后、读取消息内容输入之前的位置
- 校验规则为:只要用户输入的内容不属于
encode、decode两个合法值,就弹出无效提示,要求用户重新输入,直到输入合法后再推进原有流程 - 整段校验嵌套在原本写的
while should_continue大循环内部,不会打乱原有“选择功能→输入待处理文本→输入位移值→输出处理结果→询问是否重启运行”的逻辑顺序
改动后的完整可运行代码
#from art import logo #print(logo) 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 caesar(start_text, shift_amount, cipher_direction): end_text = "" if cipher_direction == "decode": shift_amount *= -1 for char in start_text: if char in alphabet: position = alphabet.index(char) new_position = position + shift_amount end_text += alphabet[new_position] else: end_text += char print(f"\nHere's the {cipher_direction}d result: {end_text}") should_continue = True while should_continue: direction = input("\nType 'encode' to encrypt, type 'decode' to decrypt: ").strip().lower() # 以下为新增校验逻辑,原有代码未做结构调整 while direction not in ("encode", "decode"): print("输入无效,请仅输入 'encode' 或 'decode' 进行重试。") direction = input("\nType 'encode' to encrypt, type 'decode' to decrypt: ").strip().lower() text = input("\nType your message: ").lower() shift = int(input("\nType the shift number: ")) shift = shift % 26 caesar(start_text=text, shift_amount=shift, cipher_direction=direction) result = input("\nType 'yes' if you want to go again, otherwise type 'no': ").lower() if result == "no": should_continue = False print("\nGoodbye!")
方案适配说明
- 完全未改动原代码中
caesar函数的处理逻辑、位移值取模计算、循环退出判断、结束提示等代码段,符合不修改整体逻辑的要求 - 校验环节顺带对用户输入做了去首尾空格、转小写的兼容处理,即使用户输入时不小心带了多余空格、输入了大写字母,也不会被判定为非法输入
- 非法输入场景下不会跳转到后续交互步骤,只会停在功能选择环节持续提示,直到用户输入合法值后才会继续执行后续流程
内容的提问来源于stack exchange,提问作者Kurdish Learner
相关产品推荐
相关产品推荐

