Zathura
Zathura

Reputation: 47

Why do I keep getting the error "IndexError: list index out of range"?

I don't understand why I am getting this error when I don't believe I am looping out of bounds. The error appears to be in x = lowercase[i + self.num]

class Cipher:
        def __init__(self, string, num):
            self.string = string
            self.num = num
    
    def encrypt(self):
        lowercase = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
                     'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
        uppercase = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N'
                     'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
        # establish the array from the inputed string
        split = []
        for x in range(len(self.string)):
            split.append(self.string[x])

        for x in split:
            for i in range(len(lowercase)):
                if (x == lowercase[i]):
                    x = lowercase[i + self.num]
                    print(x)


test = Cipher("hello", 1)
test.encrypt()

Upvotes: 1

Views: 178

Answers (2)

tomo_iris427
tomo_iris427

Reputation: 158

x = lowercase[i + self.num] raised index Error if i=25 and self.num=2, so you should use x = lowercase[(i + self.num)%26]

In addition, split = list(self.string) is the better method if you want to convert string to list.

Upvotes: 1

DYZ
DYZ

Reputation: 57033

There is no letter after Z (or z). You have to designate the "next" letter, which is usually A (and a). Therefore, [i + self.num] must be [(i + self.num) % len(lowercase)]. The modulo operator wraps the search around.

Upvotes: 3

Related Questions