这是我的塞萨尔密码,但第22行错了.找不到字符串



这是我正在制作的凯撒密码。我在使用substrings时遇到了一些问题。错误代码说在第22行找不到子字符串,我不知道如何修复它。请帮忙。

    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    La = len(alphabet)
    message = input("Insert your message: ")
    key = int(input("Insert your key: "))
    cipher = ''
    for A in message:
        if A in alphabet:
            cipher += alphabet[(alphabet.index(A)+key)%La]
        else:
            print ("Error")
    print(cipher)
    cipher2 = ''
    question = input("Do you wish to decrypt?: ")
    if question == "Y" or "y":
        for A in message:
            if A in alphabet:
                print(cipher.index(A))
                cipher2 += cipher[(cipher.index(A)+key)%La]
            else:
                print ("Error")
        print(cipher)
    else:
        print("Thank you")

程序中有不少错误。直接的问题是,您的第二个循环遍历原始消息,而不是密码。将第19行改为:

for A in cipher:

这将导致下一个错误,即当您尝试解密单个字母时索引超出范围。

这里不是进行推测性调试的地方。我建议你在自己的水平上找到一个调试教程,也许可以用搜索短语"我如何调试我的程序?"

对于初学者来说,当你有一个你不理解的执行错误时,重构问题陈述,并"询问患者哪里受伤"。例如,你的原始代码

for A in message:
    if A in alphabet:
        print(cipher.index(A))

变成。。。

for A in message:
    print "CHECKPOINT 1", message, A
    if A in alphabet:
        print "CHECKPOINT 2", cipher
        A_pos = cipher.index(A)
        print "CHECKPOINT 3", A_pos
        print(cipher.index(A))

试试你的解密语句:

        decode_pos = A_pos + key
        print "CHECKPOINT 4", decode_pos
        decode_pos %= La
        print "CHECKPOINT 5", decode_pos, len(cipher)
        clear_char = cipher[decode_pos]
        print "CHECKPOINT 6", clear_char
        cipher2 += clear_char
        print "CHECKPOINT 7", cipher2

这能让你动起来吗?它很严厉,但很有效。

相关内容

最新更新