Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Caesar shift cipher
cipher = input("Give me the text to encode or decode: ")
# invalid offset to ensure the while loop runs
offset = 99
result = ""
while offset < -25 or offset > 25:
    offset = int(input("Give me an offset between -25 and 25: "))
# for each character in the input text...
for c in cipher:
    # get the ASCII code
    charcode = ord(c)
    # if it's an upper case letter...
    if charcode >= 65 and charcode <= 91:
      # subtracting 39 makes A=26, B=27, etc.
      # this ensures we don't go negative if the 
      # offset is negative.  Using modular arithmetic
      # ensures that 26 wraps around 0 and Z wraps
      # back round to A.
      charcode = (charcode - 39 + offset) % 26 + 65
    # if it's a lower case letter
    if charcode >= 97 and charcode <= 122:
      # subtracting 71 makes a=26, b=27, etc.
      charcode = (charcode - 71 + offset) % 26 + 97
    result = result + chr(charcode)

print("If you shift '" + cipher + "' by " + str(offset) + " letter" + "s"*(offset != 1) + " you get '" + result + "'.")