-3
def main():
    text = input("Please enter text")
    translated = caesar(text)

    print(text,"ciphered is", translated)



def caesar(text):



        key = int(input("Please enter key shift"))
        key = key % 26

        translated = ""
        for letter in text:
            if letter.isalpha():
                num = ord (letter)
                num += key
                if letter.isupper():
                        if num > ord ('Z'):
                             num -=26
                        elif num < ord ('A'):
                              num += 26
                        elif letter.islower():
                                  if num > ord ('z'):
                                        num -= 26
                        elif num < ord ('a'):
                             num += 26
                             translated += chr(num)
                else:
                        translated += letter
            return translated

main()

So far I have this but it's not actually shifting the word, for instance if I put a shift length of 3 in, "Hello" gets shifted to just "o" and "a" doesn't won't get shift at all, can anyone help me please?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
eliot
  • 11
  • 3
  • Related: http://codereview.stackexchange.com/questions/32694/python-caesars-cipher-how-could-i-do-it-better – kojiro Mar 18 '15 at 11:40
  • Caesar Cipher is to encryption as the [Teacup ride](http://en.wikipedia.org/wiki/Teacups) is to transportation. – kojiro Mar 18 '15 at 11:42
  • @kojiro I'm not sure that's accurate; teacup rides have never been a practical means of transportation, whereas even simple substitution cyphers were once perfectly adequate for protection! Perhaps it is fairer to say it is to encryption as the litter is to transportation. – jonrsharpe Mar 18 '15 at 11:53
  • 3
    You have some serious indentation errors in your code. Check that each statement in a block is indented by 4 spaces. In Python, logic flow (partially) is determined by indentation. Check when the `translated += chr(num)` statement really is executed now. – user1016274 Mar 18 '15 at 11:55

1 Answers1

0

Reference: "Caesar Cipher with Python" http://inventwithpython.com/chapter14.html

def main():
text = input("Please enter text: ")
translated = caesar(text)

print(text,"ciphered is", translated)



def caesar(message):
key = int(input("Please enter key shift: "))
key = -key
translated = ''

for symbol in message:
    if symbol.isalpha():
        num = ord(symbol)
        num += key

        if symbol.isupper():
            if num > ord('Z'):
                num -= 26
            elif num < ord('A'):
                num += 26
        elif symbol.islower():
            if num > ord('z'):
                num -= 26
            elif num < ord('a'):
                num += 26
        translated += chr(num)
    else:
        translated += symbol
return translated

main()
logic
  • 1,739
  • 3
  • 16
  • 22