Tuesday, October 8, 2019

Caesar Cipher in Python

def encode(string, shift):
  s = ""
  for c in string:
    c = ord(c)
    if (c >= 65 and c <= 90):
      c += shift
      if c > 90:
        c -= 26
    if (c >= 97 and c <= 122):
      c += shift
      if c > 122:
        c -= 26
    c = chr(c)
    s += c
  return s

def decode(string, shift):
  s = ""
  for c in string:
    c = ord(c)
    if (c >= 65 and c <= 90):
      c -= shift
      if c < 65:
        c += 26
    if (c >= 97 and c <= 122):
      c -= shift
      if c < 97:
        c += 26
    c = chr(c)
    s += c
  return s

s = input("Enter string: ")
shift = int(input("Enter shift: "))
s = encode(s, shift)
print(s)
s = decode(s, shift)
print(s)

#########  OUTPUT ###############
Enter string: Attack at dawn
Enter shift: 2
Cvvcem cv fcyp
Attack at dawn

No comments:

Post a Comment