Python实现凯撒密码时for循环结合ord()无法遍历完整字符串问题
问题根因
你的判断完全准确,问题出在return语句的位置错误:
当前代码把return code写在了for循环内部,程序处理完第一个字符(也就是字符串里的a)时,就会立刻执行return语句终止整个函数,后续的循环逻辑根本不会运行,自然只能输出第一个字符位移后的结果b,拿不到完整的加密串。
修复方案
- 在循环外部初始化一个空字符串,用来存储所有字符加密后的结果
- 循环过程中,每计算完一个字符的位移结果,就把它追加到结果字符串末尾,不要在循环内执行return
- 等整个循环遍历完所有字符、所有加密逻辑都执行完毕后,再把拼接好的完整结果返回
修正后可运行代码
def cCipher(text,shift): #First identify whether text is a string or note. if type(text) != str: return "The input is not a string" #Get the ord() for each letter in string and shift else: result = "" # 循环外初始化结果存储变量 for i in range(len(text)): shifted_code = chr(ord(text[i])+shift) result += shifted_code # 逐字符拼接结果,不提前返回 return result # 全量字符处理完成后再返回最终结果 #This will be my test functions print(cCipher('abc', 1))
运行上述代码,会输出预期结果bcd。
额外小优化:Python遍历字符串时不需要通过索引取值,可以直接迭代字符串本身,代码更简洁,循环部分可以改写为:
result = "" for char in text: result += chr(ord(char) + shift) return result
内容的提问来源于stack exchange,提问作者quigley
相关产品推荐
相关产品推荐

