Encryption and Decryption within the alphabet - Python GCSE

前端 未结 1 900
-上瘾入骨i
-上瘾入骨i 2021-01-29 14:23

I am currently trying to write a program, for school, in order to encrypt and decrypt a inputted message. I need the encrypted or decrypted message to only be in the alphabet no

相关标签:
1条回答
  • 2021-01-29 14:50
    def getOffset():
        offset = -1
        while not 0 < offset < 25:
            try: offset = int(input("Please enter an integer offset between 1 and 25: "))
            except ValueError: continue
        return offset
    
    
    def encrypt(msg, offset):
        base = ord('a')
        chars = (ord(char)-base for char in msg)
        cipher = (base + ((c+offset)%26) for c in chars)
        return ''.join([chr(c) for c in cipher])
    
    
    decrypt = lambda msg,offset: encrypt(msg, -offset)
    
    
    def main():
        msg = """Please choose 
    [1] to encrypt
    [2] to decrypt
    [3] to exit
    """
    
        funcs = {1: encrypt, 2: decrypt}
    
        while True:
            try: choice = int(input(msg))
            except ValueError: continue
    
            if choice == 3: return
            message = input("Please enter the message that you would like to {}: ".format(funcs[choice].__name__))
            offset = int(input("Please enter the offset: "))
            print(funcs[choice](message, offset))
    
    0 讨论(0)
提交回复
热议问题