gpt4 book ai didi

python - 凯撒密码只返回第一个翻译的字母?

转载 作者:太空宇宙 更新时间:2023-11-04 05:51:07 25 4
gpt4 key购买 nike

为什么我的加密函数只返回第一个翻译后的字母? (我已经删除了解密和蛮力功能)。这个问题可能是一个小问题,但我对此并不陌生,而且我已经盯着它看了太久,以至于我脑子里什么都想不起来。

import string

def encrypt(message,key):
cryptotext=""
for character in message:
if character in string.uppercase:
old_ascii=ord(character)
new_ascii=(old_ascii+key-65)%26+65
new_char=chr(new_ascii)
cryptotext+=new_char
return cryptotext

elif character in string.lowercase:
old_ascii=ord(character)
new_ascii=(old_ascii+key-97)%26+97
new_char=chr(new_ascii)
cryptotext += new_char
return cryptotext

else:
return character

最佳答案

return 语句从当前循环中断,这意味着加密函数应该等到循环结束后返回:另请注意,如果字符不是大写或小写,则应附加该字符,否则它只会返回第一个错误的字母。
所以 encrypt(message,key) 应该是这样的:

def encrypt(message,key):
cryptotext=""
for character in message:
if character in string.uppercase:
old_ascii=ord(character)
new_ascii=(old_ascii+key-65)%26+65
new_char=chr(new_ascii)
cryptotext+=new_char


elif character in string.lowercase:
old_ascii=ord(character)
new_ascii=(old_ascii+key-97)%26+97
new_char=chr(new_ascii)
cryptotext += new_char


else:
#Also, append character to cryptotext instead of returning it
cryptotext+= character
return cryptotext

关于python - 凯撒密码只返回第一个翻译的字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30153883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com