python 3.4 - I'm trying to re-create a Caesar Cipher by reading said text from a file and encrypting by 2 keywords -


basically, program when run comes error 'output2.append(chr(base + (ord(letter)- base + newkey2[pos]) % 26)) indexerror: list index out of range'
here code:

base = ord('a') choice = input("would encrypt?") key = input("please enter keyword encrypt by: ").upper() key2 = input("please enter keyword encrypt by: ").upper() #keyword upper case key = [ord(letter)- base + 1 letter in key] key2 = [ord(letter)- base + 1 letter in key2] count = 0 #this sets count 0 file = open("test.txt","r") while true:     msg = ''.join(chr chr in file)     if not chr in file: break  newkey = (key*len(msg))[:len(msg)]  newkey2 = (key2*len(msg))[:len(msg)]      output = [] output2 = [] pos = 0   letter in msg:     output.append(chr(base + (ord(letter)- base + newkey[pos]) % 26))     pos += 1 print(output)  letter in output:     output2.append(chr(base + (ord(letter)- base + newkey2[pos]) % 26))     pos += 1 print(output2) print("your encrypted message is:", ''.join(output2))         file.close() 

your pos doesn't automatically reset 0, why getting error. after loop for letter in msg:, pos variable len(msg). trying access index in next loop, , still incrementing pos. mean aren't accessing newkwy2[0], newkey2[1], newkey2[2], ... newkwy2[len(msg)], newkey2[len(msg) + 1], newkey2[len(msg) + 2], ...

to avoid error, can either reset variable 0 between loops or try this:

for index, letter in enumerate(output):     output2.append(chr(base + (ord(letter)- base + newkey2[index]) % 26)) 

this way don't need use pos variable.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -