Question

Here is an example:

  • Plain: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  • Shift = 4
  • Cipher:DEFGHIJKLMNOPQRSTUVWXYZABC

Here is the code:

print ("This is a cyclic cipher program that will encrypt messages.")

#phrase = input("Please enter a phrase to encrypt.")
phrase = "ABCDEFG"
#shift_value = int(input ("Please enter a shift value between 1 - 5."))
shift_value = 1
encoded_phrase = ""
ascii_codes = 0
x = ""
#accepted_ascii_codes = range(65,90) and range(97,122)

for c in phrase:
ascii_codes = ord(c) # find ascii codes for each charcter in phrase
ascii_codes = ascii_codes + shift_value # add an integer (shift value) to ascii codes
phrase_rest = chr(ascii_codes) # convert ascii codes back to characters
encoded_phrase = encoded_phrase + c # stores the phrase character in a new variable
encoded_phrase = encoded_phrase.replace(c,phrase_rest) # replace original character

print (phrase) # prints "ABCDEFG"
print (encoded_phrase) # prints "HHHHHHH"
Was it helpful?

Solution

You are re-encoding your cyphered letter on each loop, this would do the trick:

for c in phrase:
  ascii_codes = ord(c) # find ascii codes for each charcter in phrase
  ascii_codes = ascii_codes + shift_value # add an integer (shift value) to ascii codes
  phrase_rest = chr(ascii_codes) # convert ascii codes back to characters
  encoded_phrase = encoded_phrase + phrase_rest # stores the phrase character in a new variable

however, you might want to set up a dictionary with the original letter and the cyphered one. You would then loop over them and get the cyphered sentence. For instance:

cypher = {'a': 'x', 'b': 'y', ... }
encoded = ''
for c in phrase:
  encoded += cypher[c]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top