Charlie Bewsey
Charlie Bewsey

Reputation: 19

How do I add list items from different lists in python?

I am trying to create a one-time pad-esque cipher in python. To do this I am converting all of the plain text and then the key to ASCII code, then adding them together, then converting them back to regular characters. However, I have gotten stuck when I try to add the two numbers together. Here is my code:

#Creating initial variables
plainText = str(input('Input your plain text \n --> ')).upper()
key = str(input('Input your key. Make sure it is as long as your plain text.\n --> ')).upper()

#>Only allowing key if it is the same size as the plain text
if len(key) != len(plainText):
    print('Invalid key. Check key length.')
    key = str(input('Input your key. Make sure it is as long as your plain text. \n --> ')).upper()
else:
    plainAscii=[ord(i) for i in plainText]
    keyAscii=[ord(k) for k in key]

print (plainAscii)
print (keyAscii)

#Adding the values together and putting them into a new list
cipherText=[]
for i in range(0, len(key)):
    x = 1
    while x <= len(key):
        item = plainAscii[x] + keyAscii[x]
        cipherText.append(item)
        x = x + 1
print(cipherText)

I am printing the lists as I go along for testing. However it only returns this after printing the first two lists:

 Traceback (most recent call last):
  File "/Users/chuckii/Desktop/onetimepad.py", line 21, in <module>
    item = plainAscii[x] + keyAscii[x]
IndexError: list index out of range

Please ignore my juvenile username, I made it when I was 10. Thanks in advance.

Upvotes: 0

Views: 55

Answers (1)

Carl
Carl

Reputation: 2067

Edit with more efficiency:

cipherText=[]

for i in range(len(key)):
    for x in range(len(key)):
        item = plainAscii[x] + keyAscii[x]
        cipherText.append(item)

print(cipherText)

Should solve it!

Upvotes: 1

Related Questions