该指数超出范围的是哪里?

时间:2014-12-24 13:44:52

标签: python string encryption reference

我正在编写一个使用密钥加密和解密的算法。或者说我有,这更像是重写我的代码。无论如何,我刚刚开始构建基于文本的界面,Tkinter将在稍后出现。

当索引一个Key时,我设置为12345,我得到一个“IndexError:字符串索引超出范围”。我知道这意味着什么。但我也知道整个字符串在循环中被索引。从0开始。这是它得到错误的地方。我甚至试过单独测试它,例如打印(密钥[0]) 但Python仍然会抛出错误。我不明白为什么。它引用字符串12345为0,应返回1.

Do you want to encrypt or decrypt? encrypt
Input a string toencrypt- Hello123
Input a key- 12345
123451
1234512
12345123
Key = 
Traceback (most recent call last):
  File "C:\Users\Theo_2\Google Drive\Computer science\Encryption and decryption work\Cipher 2\Cipher 2.5.0 Beta .py", line 142, in <module>
    User_text_interface(True)
  File "C:\Users\Theo_2\Google Drive\Computer science\Encryption and decryption work\Cipher 2\Cipher 2.5.0 Beta .py", line 137, in User_text_interface
    print(str(Encrypt(User_input)))
  File "C:\Users\Theo_2\Google Drive\Computer science\Encryption and decryption work\Cipher 2\Cipher 2.5.0 Beta .py", line 27, in Encrypt
    print(Key[0])
IndexError: string index out of range

以下是我的代码:

具体来说,我认为我的问题出在Encrypt函数中,尽管它也可能在Decrypt中。请忽略中间注释掉的东西,我通过加密和解密循环运行每一个值都很好

import time, sys
Master_Key = "0123456789 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#£$%&'()*+,-./:;?@[\\]^_`{|}~\t\n\r\x0b\x0c"
global Output
Output = ""
global Key
Key = ""
##global User_input
def Compatibility_check(Key, User_input):
    Temp = 0
    while Key == "":  
        print("Your key cannot be blank")
        Key = input("Please input a new key: ")
    while len(Key) > len(User_input):
        Key = Key[:-1]
    while len(Key) < len(User_input):
        Key += (Key[Temp])
        Temp += 1
        print(Key)

def Encrypt(User_input):
    ##Compatibility_check(Key)
    Count = 0
    global Output
    Output = ""
    while Count < len(User_input):
        print(Key[0])
        print("Count = " + str(Count))
        print("Key count = " + str(Key[Count]))
        print("Master_key.index")
        print("Testing- Input indexer- " + str(Master_Key.index(User_input[Count])))
        print("Testing- Key indexer- " + str(Master_Key.index(Key[Count])))


        ref_for_output = Master_Key.index(User_input[Count]) + Master_Key.index(Key[Count])
        if ref_for_output >= len(Master_Key): ## As [] starts from zero
            ref_for_output -= len(Master_Key)
        Output += Master_Key[ref_for_output]
        Count += 1
    ##print("Output is " + Output)
    return Output

def Decrypt(User_input):
    ##Compatibility_check(Key)
    Count = 0
    global Output
    Output = ""
    while Count < len(User_input):
        ref_for_output = Master_Key.index(User_input[Count]) - Master_Key.index(Key[Count])
        if ref_for_output < 0:
            ref_for_output += len(Master_Key)
        Output += Master_Key[ref_for_output]
        Count += 1
    ##print("Output is " + Output)
    return Output

def Test_algorithm(Null):
    Counter1 = 0
    while Counter1 < (len(Master_Key)-1): ##If <= doesnt work use (len(Master_Key)-1)
        Input, Counter2 = Master_Key[Counter1], 0
        print("Input = " + Input)
        Counter1 += 1
        print("Loop 1")
        if Counter1 == len(Master_Key):
            print("The program works.")
        while Counter2 < (len(Master_Key)-1):
            global Key
            Key = Master_Key[Counter2]
            Encrypt(Input)
            ##Temp = Output
            Decrypt(Output)
            print("Encryption and decryption of Input- " + str(Input) + " with the Key- " + str(Key) + " results in an output of " + str(Output))
            if Input == Output:
                print("Pass")
            else:
                print("Fail")
                sys.exit
            Counter2 += 1
            ##Counters are used here, it is simply easier to use a counter and a while loop when dealing with references from a for loop

def User_text_interface(Repeat):
    while Repeat == True:
        ED = input("Do you want to encrypt or decrypt? ")
        User_input = input("Input a string to" + str(ED) + "- ")
        Key = input("Input a key- ")
        Compatibility_check(Key, User_input)
        if ED.lower() == "encrypt" or ED.lower() == "e":
            print(str(Encrypt(User_input)))
        elif ED.lower() == "decrypt" or ED.lower() == "d":
            print(str(Decrypt(User_input)))


User_text_interface(True)

2 个答案:

答案 0 :(得分:2)

您的Key变量是一个空字符串:

>>> Key = ''
>>> Key[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

那是因为您永远不会更改全局 Key变量,只能更改本地变量。 global语句必须放在函数中:

def Compatibility_check(Key, User_input):
    global Key
    Temp = 0
    while Key == "":  
        print("Your key cannot be blank")
        Key = input("Please input a new key: ")
    while len(Key) > len(User_input):
        Key = Key[:-1]
    while len(Key) < len(User_input):
        Key += (Key[Temp])
        Temp += 1
        print(Key)

但是让函数返回新值更好;你使用return Key(结束函数)然后分配返回值:

Key = Compatibility_check(Key, User_input)

答案 1 :(得分:0)

原来我的问题很明显。这是我编写兼容性检查功能的方式。 基本上它需要两个输入,Key和User_input。 所以它应该检查Key以获取各种各样的东西,如果它不符合它们就改变它。不幸的是,我忽略了这样一个事实:它只是改变了它的内部变量'Key',它与后来使用的'Key'同名。

这意味着密钥短于输入,我的加密函数试图引用Key中不存在的字符。