Jane
Jane

Reputation: 41

Python Encryption & Decryption

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?

Upvotes: 0

Views: 2333

Answers (1)

Laurent S
Laurent S

Reputation: 4326

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 :)

Upvotes: 1

Related Questions