为什么我的加密功能只返回第一个翻译的字母? (我已经删除了解密和暴力功能)。这个问题可能很小,但我对此并不熟悉,而且我已经盯着它看了太长时间没有任何东西可以进入我的脑海。
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
答案 0 :(得分: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
答案 1 :(得分:0)
您将return
语句放在循环中。这意味着在第一次迭代后退出函数,结果只有一个字符。
您的代码应如下所示:
cryptotext = ""
for character in message:
# ...
# do the encryption, without returning
# ...
return cryptotext # after the loop has finished