Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index Error in python

I am new to programming, and I am trying to write a Vigenère Encryption Cipher using python. The idea is very simple and so is my function, however in this line:

( if((BinKey[i] == 'b')or(BinKey[i+1] == 'b')): ) 

It seems that I have an index problem, and I can't figure out how to fix it. The error message is:

IndexError: string index out of range

I tried to replace the i+1 index by another variable equal to i+1, since I thought that maybe python is re-incrementing the i, but it still won't work.

So my questions are:

  1. How to fix the problem, and what have I done wrong?

  2. Looking at my code, what can I learn to improve my programming skills?

  3. I want to build a simple interface to my program (which will contain all the encryption ciphers), and all I came up with from Google is pyqt, but it just seems too much work for a very simple interface, so is there a simpler way to build an interface? (I am working with Eclipse Indigo and pydev with Python3.x)

The Vigenère Encryption function (which contains the line that causes the problem) is:

def Viegner_Encyption_Cipher(Key,String):
    EncryptedMessage = ""
    i = 0
    j = 0
    BinKey = Bin_It(Key)
    BinString = Bin_It(String)
    BinKeyLengh = len(BinKey)
    BinStringLengh = len(BinString)
    while ((BinKeyLengh > i) and (BinStringLengh > j)):
        if((BinKey[i] == 'b')or(BinKey[i+1] == 'b')):
            EncryptedMessage = EncryptedMessage + BinKey[i]
        else:   
            EncryptedMessage = EncryptedMessage + Xor(BinKey[i],BinString[j])
        i = i + 1
        j = j + 1
        if (i == BinKeyLengh):
            i = i+j
    return EncryptedMessage

This is the Bin_It function:

 def Bin_It(String):
    TheBin = ""
    for Charactere in String:
         TheBin = TheBin + bin(ord(Charactere))
    return TheBin

And finally this is the Xor function:

def Xor(a,b):
    xor = (int(a) and not int(b)) or (not int(a) and int(b))
    if xor:
        return chr(1)
    else:
        return chr(0)
like image 236
hamza Avatar asked Dec 20 '22 13:12

hamza


1 Answers

In your while condition, you are ensuring that i < len(BinKey). This means that BinKey[i] will be valid, but BinKey[i+1] will not be valid at the last iteration of your loop, as you will then be accessing BinKey[len(BinKey)], which is one past the end of your string. Strings in python start at 0 and end at len-1 inclusive.

To avoid this, you can update your loop criterion to be

while BinKeyLength > i+1 and ...:
like image 117
amaurea Avatar answered Jan 02 '23 22:01

amaurea