-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?

4

1 回答 1

0

参考:“凯撒密码与 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()
于 2015-03-18T12:59:09.937 回答