具有先决条件功能的凯撒密码



我正在学习python的在线课程,我们目前正在研究凯撒密码。 我已经在这个网站上看到了许多关于该主题的回答问题,但没有一个警告是必须必须使用以前的函数,例如在我的代码中。 当我使用多个输入测试它们时,前两个函数工作正常,但是当我添加最后一个函数加密时,我得到找不到子字符串的值错误。 我不知道我应该为最后一部分做什么。 有没有人有建议可以推动我朝着正确的方向前进?

def alphabet_position(letter):
    alphabet ="abcdefghijklmnopqrstuvwxyz" #Lists alphabet for a key
    lower_letter = letter.lower()   #Makes any input lowercase.
    return alphabet.index(lower_letter) #Returns the position of input as a number.
def rotate_character(char, rot):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    if char.isalpha():
        a = alphabet_position(char) 
        a = (a + rot) % 26            #needs modulo
        a = (alphabet[a])
        if char.isupper():
            a = a.title()
        return a
    else:
       return char
def encrypt(text, rot):
    list1 = ""
    for char in text:
        list1 += rotate_character(text, rot)
    return list1
def main():
    x = input("Type a message: ")
    y = int(input("Rotate by: "))
    #result = rotate_character(x, y)  #Not needed once encrypt function works.
    result = encrypt(x, y)
    print (result)
if __name__ == '__main__':
    main()

您希望单独旋转每个字符,但要将完整的文本传递给旋转函数。

而是使用:

def encrypt(text, rot):
    list1 = ""
    for char in text:
        list1 += rotate_character(char, rot) # "char", not "text"
    return list1

最新更新