凯撒密码只返回第一封翻译的信?

2024-09-30 08:14:34 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么加密函数只返回第一个翻译的字母?(我去掉了解密和暴力功能)。这个问题可能是一个小问题,但我是新来的,我已经盯着它太久了,任何东西弹出我的脑海。你知道吗

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

Tags: key函数inmessagenewstringreturn字母
2条回答

return语句从当前循环中断,这意味着encrypt函数应该等到循环结束后返回: 另外请注意,如果字符不是大写或小写,则应附加字符,否则只会返回错误的第一个字母。
所以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

return语句放入循环中。这意味着在第一次迭代之后,您将退出函数,结果只有一个字符。你知道吗

您的代码应该如下所示:

cryptotext = ""
for character in message:
    # ...
    # do the encryption, without returning
    # ...
return cryptotext # after the loop has finished

相关问题 更多 >

    热门问题