Caesar's Cipher using python, could use a little help

后端 未结 8 1392
时光说笑
时光说笑 2020-11-30 14:24

I\'m trying to make a \"Caesar\'s Cipher\" while using python..this is what I have so far. Could anyone tell me how this is looking? Am I going in the right direction? What

8条回答
  •  [愿得一人]
    2020-11-30 15:03

    This code should work pretty well. It also handles arbitrary offsets, including negative.

    phrase = raw_input("Please enter plaintext to Cipher: ")
    shift = int(raw_input("Please enter shift: "))
    
    result = ''
    for char in phrase:
        x = ord(char)
    
        if char.isalpha():
            x = x + shift
    
            offset = 65
            if char.islower():
                offset = 97
    
            while x < offset:
                x += 26
    
            while x > offset+25:
                x -= 26
    
            result += chr(x)
    
    print result
    

    The other way to do it, with a slightly different cipher, is simply rotate through all characters, upper and lower, or even all ascii > 0x20.

    phrase = raw_input("Please enter plaintext to Cipher: ")
    shift = int(raw_input("Please enter shift: "))
    
    result = ''
    for char in phrase:
        x = ord(char)
    
        x = x + shift
    
        while x < 32:
            x += 96
    
        while x > 127:
            x -= 96
    
        result += chr(x)
    
    print result
    

提交回复
热议问题