Reputation: 673
I've seen other programs that encrypt text, however they tend to be quite long winded - and I'm relatively new to python. I've had a go at encrypting something (It is quite simple) and I can get each character turned into ASCII, it's value changed and then turned back. But when I run the code, only the last character is displayed in the list, why is this and what have I done wrong???
message = input('What should I encrypt? ')
for i in range(len(message)):
num = ord(message[i])
num += 3
Chr = chr(num)
Message = []
Message.append(Chr)
print(Message)
Upvotes: 1
Views: 54
Reputation: 653
message = input('What should I encrypt? ')
secret = []
for i in range(len(message)):
num = ord(message[i])
num += 3
secret.append(chr(num))
print(secret)
You were redefining Message
(in my code secret
) over and over through each iteration, therefore when the for
-loop has ended you got only the last character. Moving the Message = []
before the for-loop fixes the issue.
You can iterate through characters in the string directly (when you do not need the index), like for char in message: do_stuff()
.
Example here:
message = input('What should I encrypt? ')
secret = []
for char in message:
num = ord(char) + 3
secret.append(chr(num))
print(secret)
Upvotes: 2