This is my code:
from tkinter import messagebox, simpledialog, Tk
def is_even(number):
return number % 2 == 0
def get_even_letters(message):
even_letters = []
for counter in range(0, len(message)):
if is_even(counter):
even_letters.append(message[counter])
return even_letters
def get_odd_letters(message):
odd_letters = []
for counter in range(0, len(message)):
if not is_even(counter):
odd_letters.append(message[counter])
return odd_letters
def swap_letters(message):
letter_list = []
if not is_even(len(message)):
message = message + 'x'
even_letters = get_even_letters(message)
odd_letters = get_odd_letters(message)
for counter in range(0, int(len(message)/2)):
letter_list.append(odd_letters[counter])
letter_list.append(even_letters[counter])
new_message = ''.join(letter_list)
return new_message
def get_task():
task = simpledialog.askstring('Task', 'Do you want to encrypt or decrypt?')
return task
def get_message():
message = simpledialog.askstring('Message', 'Enter the secret message')
return message
root = Tk()
while True:
task = get_task()
if task == 'encrypt':
message = get_message()
encrypted = swap_letters(message)
messagebox.showinfo('Ciphertext of the secret message is:', encrypted)
elif task == 'decrypt':
message = get_message()
decrypted = swap_letters(message)
messagebox.showinfo('Plain text of the secret message is: ', decrypted)
else:
break
root.mainloop()
Currently using IDLE, Python 3.6.3. Whenever I run the program, the first prompt works, 'encrypt', but when I get to the 'Enter the secret message' prompt, if I type anything with more than 2 letters, it gives me the error:
Traceback (most recent call last):
File "/Users/richarddao/Documents/secret_message.py", line 46, in <module>
encrypted = swap_letters(message)
File "/Users/richarddao/Documents/secret_message.py", line 28, in swap_letters
letter_list.append(even_letters[counter])
IndexError: list index out of range
What is IndexError: list index out of range? How do I fix this?
Index Error: List index out of range
means you are trying to get an item in a list that doesn't exist.
For Example, I have this list:
["a","b","c"]
So a is the 0th item, b is the 1st, and c is the 2nd.
I can get b by doing ["a","b","c"][1]
because it is the first item and I am calling for the first item with [1].
An index error is what would happen if I tried to do this:
["a","b","c"][4]
There is no 4th item, so it errors.