0

I am trying to encrypt a user-input message.

My code:

#encrypt
user_input = input ("Enter string: ")
for char in user_input: #for every character in input
    cipher_num = (ord(char))+3%26 #using ordinal to find the number
    cipher= ''
    cipher = chr(cipher_num) # using chr to convert back to a letter
    cipher_text = '' #add all values to string
    cipher_text = (cipher_text+cipher)
print (cipher_text)

#decrypt
for char in cipher_text: #for every character in the encrpted text
    decrypt_num = (ord(char))-3%26
    decrypt= ''
    decrypt = chr(decrypt_num)
    decrypt_text = ''
    decrypt_text = (decrypt_text+decrypt)
print(decrypt_text)

The output I am receiving is-

Enter string: abc

f

c


Why is it only giving me the encrypted value of the last character in the string?

Jane
  • 41
  • 2
  • 7

1 Answers1

1

In your loop, you have

 cipher_text = '' #add all values to string

which resets cipher_text to an empty string. Your code says at each loop: "empty cipher_text and put one character in it".

You need to move that line out of the for loop.

Your code should look like this instead:

cipher_text = ''  # initialise the string
for char in user_input:
    cipher_num = (ord(char))+3%26
    cipher= ''   # you don't need this line as the next one overwrites the variable
    cipher = chr(cipher_num)
    cipher_text = cipher_text + cipher
    # you can shorten the line above to: cipher_text += cipher

The same happens for decrypt_text.

There are many ways you can simplify this code, and make it more pythonic, but that's for another question :)

Laurent S
  • 4,106
  • 3
  • 26
  • 50
  • Thanks! Also, whenever I print something with a space, the output had # instead of the space. I tried using sep=" ", but it doesnt seem to work. Any suggestions? – Jane Mar 15 '17 at 05:24
  • It sounds like a different question. It's probably best if you accept this answer (or not if you're not happy with it) and post another question, where you include your code. Also, seeing the problems you're facing, you might want to take a look at http://learnpythonthehardway.org/ to get a better understanding of the basics of python. It's a great intro, highly recommended! – Laurent S Mar 15 '17 at 05:31