0

Um, another error, another thread? O.o Well, anyway, here's the code:

import cs50
import sys

if len(sys.argv) == 1 or len(sys.argv) > 2:
    print("Usage: python vigenere.py <key>")
    exit(1)

key = sys.argv[1]
for i in range(len(key)):
    if key[i].isalpha() is not True:
        print("Keyword must only contain letters A-Z or a-z")
        exit(2)

print("plaintext: ", end="")
plaintext = cs50.get_string()
plaintext_size = len(plaintext)
key_size = len(key)

ciphertext = []
j = 0
for i in range(plaintext_size):
    if j >= key_size:
        j = 0
    if plaintext[i].isalpha():
        k = ord(key[j].upper()) % 65
        ciphertext = []

        c = (ord(ciphertext[i]) + ord(key[i])) % 26
        c += ord('A')
        ciphertext.append(chr(c))
        j += 1

    else:
        c = ord(plaintext[i])
        ciphertext.append(chr(c))

print("ciphertext: ", end="")
print("".join(ciphertext))
exit(0)

The error is on line 28: c = (ord(ciphertext[i]) + ord(key[i])) % 26, and it says, "IndexError: list index out of range".

1 Answer 1

1

IndexError probably means that you are trying to access an element in a list that doesn't exist. This particular problems refers to, on line 28, that you are trying to read an index in ciphertext which doesn't even exist yet, and there's also every chance that there aren't i elements in key.

9
  • I changed the line to c = (ord(ciphertext[i]) + k) % 26 and am still getting the error, so I think I'm trying to access an element of ciphertext that's out of range. What should I do fix it? Any hints or suggestions? Commented Feb 25, 2017 at 23:03
  • Consider the first iteration of the loop. i is equal to 0, but ciphertext has yet to have any elements appended to it, it is still an empty list, so you are trying to read a variable that isn't there. Commented Feb 26, 2017 at 6:46
  • I fixed that part and took one thing out. Look at it again, please. On Pastebin here: pastebin.com/iwqrjqKY. Commented Feb 26, 2017 at 18:51
  • When you calculate the cipher letter, you can only use modulo 26 if the character is converted to an index between 0 and 25, otherwise it will not work as you hope. Commented Feb 26, 2017 at 19:03
  • Also, you don't need to declare the ciphertext list more than once. Commented Feb 26, 2017 at 19:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .