2

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

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
4

2 回答 2

1

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
于 2015-05-10T16:48:54.037 回答
0

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

您的代码应如下所示:

cryptotext = ""
for character in message:
    # ...
    # do the encryption, without returning
    # ...
return cryptotext # after the loop has finished
于 2015-05-10T16:41:17.640 回答