我的字符串索引在此密码中超出范围

时间:2018-05-21 09:09:51

标签: python

def cipherText():
    text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    key = int(input("Enter numerical key--"))
    word = str(input("Type word to be ciphered--"))
    i = 0
    k = 0
    n = len(word)
    print(n)
    while n >= 0:
        letter = word[i]
        i = i + 1
        while k <= 25:
            textLetter = text[k]
            if textLetter == letter:
                givenLetter = letter
                if k < (25 - key):
                    cipherLength = k + key
                else:
                    cipherLength = k + key - 25
                print(text[cipherLength])
            k = k + 1
        n = n - 1


cipherText()

当我按照以下消息发送时:

  

回溯(最近一次呼叫最后一次):文件&#34; main.py&#34;,第23行,in          cipherText()文件&#34; main.py&#34;,第10行,在cipherText中       letter = word [i] IndexError:字符串索引超出范围

1 个答案:

答案 0 :(得分:0)

您需要修改条件while n>=0:,因为列表以0th索引开头。

这一行,

while n>=0:

应该是,

while n-1>=0: