Home > database >  Error, index out of range. What is wrong?
Error, index out of range. What is wrong?

Time:02-04

I wrote a Python3 script to solve a picoCTF challenge. I received the encrypted flag which is: cvpbPGS{c33xno00_1_f33_h_qrnqorrs} From its pattern, I thought it is encoded using caesar cipher. So I wrote this script:

alpha_lower = ['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']
alpha_upper = ['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']
text = 'cvpbPGSc33xno00_1_f33_h_qrnqorrs '

for iterator in range(len(alpha_lower)):
    temp = ''
    for char in text:
        if char.islower():
        
            ind = alpha_lower.index(char)
            this = ind   iterator
            
            while this > len(alpha_lower):
                this -= len(alpha_lower)
                
            temp  = alpha_lower[this]
            
        elif char.isupper():
            ind = alpha_upper.index(char)
            that = ind   iterator
            
            while that > len(alpha_upper):
                that -= len(alpha_upper)

            temp  = alpha_upper[that]
    print(temp)

I understand what the error means. I can't understand where the flaw is to fix. Thanks in advance.

Sorrym here is the error:

Desktop>python this.py 
cvpbPGScxnofhqrnqorrs  
dwqcQHTdyopgirsorpsst
exrdRIUezpqhjstpsqttu
Traceback (most recent call last):
File "C:\Users\user\Desktop\this.py", line 18, in <module>
temp  = alpha_lower[this]
IndexError: list index out of range   

CodePudding user response:

I should have used modulus. :)

CodePudding user response:

Why that break is simple : If this==len(alpha_lower) then we won't enter your loop: while this > len(alpha_lower): And thus when trying temp = alpha_lower[this] it will return an error. An index must be strictly inferior to the size of the array. Your condition should have been while this >= len(alpha_lower):. As pointed out, a better method here is to use a modulus.

  • Related