加密/解密 - Python GCSE [英] Encryption/Decryption - Python GCSE

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

问题描述

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

  def find_offset():

offset = int(input输入一个偏移量:))

如果offset> 25或偏移0:
打印(无效的偏移,请输入另一个偏移量)
find_offset()
else:
print(Okay)
encrypt_fun


def encrypt_fun(offset):

choice =''
while choice!='3':
choice = input \你要加密还是解密消息?\\\
Enter 1 to Encrypt,2 to Decrypt,3 to Exit Program:)
if choice =='1':
message = input (0,len(message))


$ b result = chr(ord(message [i])+ offset )
print(result,end =''),

elif choice =='2':
message = input(\\\
将消息解密:)

为我的范围(0,len(消息)):
result = chr(ord(message [i]) - offset)
print(result,end = '),

el如果选择!='3':
print(您输入的选项无效。

find_offset()


解决方案

目前,如果您超过或低于 a(97)的顺序值,则不进行任何限制 z(122)



如果您要指定这些条件,并检查何时添加或减去您的偏移量,你会找到你想要的结果。

  LOWER_BOUND = 97 
UPPER_BOUND = 122

def alter_char(char,offset):

更改char将以字符作为输入,将序数值更改为
,然后执行一些边界检查以确保
它仍然在`a< - > z`序数范围。如果该值超出
的范围,它将进行环绕,以确保只使用字母字符


:param str char:要操作的字符
:param int offset:用于更改字符的偏移量
:return:返回改变后的字符
:rtype:str

char_ord = ord(char)+ offset
如果char_ord> UPPER_BOUND:
返回chr(LOWER_BOUND +(char_ord - UPPER_BOUND) )
如果char_ord< LOWER_BOUND:
返回chr(UPPER_BOUND - (LOWER_BOUND - char_ord)+ 1)
返回chr(char_ord)
pre>

有了这个,你可以改变你的 result = chr(ord(message [i])+ offset)行调用 alter_char 函数来确定您要查找的字符,即。

 $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ 



$ `-`在功能上相当于将
#的偏移量乘以-1,

除此之外,字符串自然是可迭代的,所以您在循环中的可以重构这样的消息:
result = alter_char(char,offset)

   

或进一步将其转化为列表理解

  result =''.join([alter_char(char,offset)for char in message])

请注意,这仍然只适用于提交加密和解密的小写短信,因为UPPER CASE字母具有不同的序数值。


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

解决方案

Currently you don't do any bounds checking for if you go over or under the ordinal value of a (97) or z (122).

If you were to specify these conditions, and check when adding or subtracting your offset, you would find the result you're looking for.

LOWER_BOUND = 97
UPPER_BOUND = 122

def alter_char(char, offset):
    """
    Alter char will take a character as input, change the ordinal value as 
    per the offset supplied, and then perform some bounds checks to ensure
    it is still within the `a <-> z` ordinal range. If the value exceeds
    the range, it will wrap-around to ensure only alphabetic characters
    are used.

    :param str char: The character you wish to manipulate
    :param int offset: The offset with which to alter the character
    :return: Returns the altered character
    :rtype: str
    """
    char_ord = ord(char) + offset
    if char_ord > UPPER_BOUND:
        return chr(LOWER_BOUND + (char_ord - UPPER_BOUND) - 1)
    if char_ord < LOWER_BOUND:
        return chr(UPPER_BOUND - (LOWER_BOUND - char_ord) + 1)
    return chr(char_ord)

With that in place, you can alter your result = chr(ord(message[i]) + offset) lines to call the alter_char function to ascertain the character you're looking for, ie.

result = alter_char(message[i], offset)  # for encryption
result = alter_char(message[i], -offset) # for decryption
# Prefixing the offset with a `-` is functionally equivalent to multiplying
# the offset by `-1`

As an aside, strings are naturally iterable, so your for i in range loop can be refactored as such

for char in message:
    result = alter_char(char, offset)

or going a step further and turning it into a list comprehension

result = ''.join([alter_char(char, offset) for char in message])

Just note, that this will still only cater for lower case messages being submitted for encryption and decryption as UPPER CASE letters have different ordinal values.

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

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