字母表内的加密和解密 - Python GCSE [英] Encryption and Decryption within the alphabet - Python GCSE

查看:270
本文介绍了字母表内的加密和解密 - Python GCSE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为学校写一个程序,以加密和解密输入的信息。我需要加密或解密的消息只能在字母表中没有其他符号或键,例如,使用消息面包车加密的输入偏移量为5,我希望它输出afs。有人可以帮忙吗?这是我当前的代码。

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 other symbols or keys, for example, with an inputted offset of 5 using the message van to encrypt, i want it to output 'afs'. Can anyone help please? This is my code currently.

def find_offset():
    offset = int(input("Enter an offset: "))
    if offset > 25 or offset < 0:
        print("Invalid offset, please enter another offset: ")
        find_offset()
    else:
        print("Okay")
        encrypt_fun(offset)


def encrypt_fun(offset):
    choice = ''
    while choice != '3':
        choice = input("\nDo you want to encrypt or decrypt the message?\nEnter 1 to Encrypt, 2 to Decrypt, 3 to Exit Program: ")
        if choice == '1':
            message = input("\nEnter the message to encrypt: ")

            for i in range(0, len(message)):
                result = chr(ord(message[i]) + offset)
                print(result, end=''),

        elif choice == '2':
            message = input("\nEnter the message to decrypt: ")

            for i in range(0, len(message)):
                result = chr(ord(message[i]) - offset)
                print(result, end=''),

        elif choice != '3':
            print("You have entered an invalid choice. Please try again.\n\n")

find_offset()


推荐答案

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

这篇关于字母表内的加密和解密 - Python GCSE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆