加密/解密-Python GCSE
我目前正试图为学校编写一个程序,以便对输入的信息进行加密和解密。我需要加密或解密的消息只在字母表中没有其他符号或密钥,例如,使用消息车加密输入的偏移量为5,我希望它输出“afs”。有人能帮忙吗?这是我目前的代码:加密/解密-Python GCSE,python,encryption,Python,Encryption,我目前正试图为学校编写一个程序,以便对输入的信息进行加密和解密。我需要加密或解密的消息只在字母表中没有其他符号或密钥,例如,使用消息车加密输入的偏移量为5,我希望它输出“afs”。有人能帮忙吗?这是我目前的代码: def find_offset(): offset = int(input("Enter an offset: ")) if offset > 25 or offset < 0: print("Invalid offset, please
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 find_offset():
偏移量=int(输入(“输入偏移量:”)
如果偏移量>25或偏移量<0:
打印(“无效偏移,请输入另一个偏移:”)
查找偏移量()
其他:
打印(“好”)
加密(偏移量)
def encrypt_fun(偏移量):
选择=“”
而选择3':
choice=input(“\n要加密还是解密消息?\n输入1进行加密,输入2进行解密,输入3退出程序:”)
如果选项==“1”:
message=input(“\n输入要加密的消息:”)
对于范围(0,len(消息))中的i:
结果=chr(ord(信息[i])+偏移量)
打印(结果,结束=“”),
elif choice==“2”:
message=input(“\n输入要解密的消息:”)
对于范围(0,len(消息))中的i:
结果=chr(ord(信息[i])-偏移量)
打印(结果,结束=“”),
伊里夫选择!='3':
打印(“您输入的选项无效。请重试。\n\n”)
查找偏移量()
当前,如果您在a(97)
或z(122)
的顺序值上下移动,则不会进行任何边界检查
如果要指定这些条件,并在添加或减去偏移量时进行检查,则会找到要查找的结果
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)
另一方面,字符串自然是可编辑的,因此可以对for i in range
循环进行重构
for char in message:
result = alter_char(char, offset)
或者更进一步,把它变成一个列表
result = ''.join([alter_char(char, offset) for char in message])
请注意,这仍然只适用于提交加密和解密的小写消息,因为大写字母具有不同的序号值
result = ''.join([alter_char(char, offset) for char in message])