使用Prompt()函数在Python中设计一个简单的加密/解密程序。
发布时间:2024-01-02 09:47:11
下面是一个简单的加密/解密程序,使用prompt()函数接受用户指令,并根据指令进行相应的加密或解密操作。
def encrypt(message, key):
encrypted_message = ""
for char in message:
if char.isalpha():
encrypted_char = chr((ord(char) + key - 65) % 26 + 65)
encrypted_message += encrypted_char
else:
encrypted_message += char
return encrypted_message
def decrypt(message, key):
decrypted_message = ""
for char in message:
if char.isalpha():
decrypted_char = chr((ord(char) - key - 65) % 26 + 65)
decrypted_message += decrypted_char
else:
decrypted_message += char
return decrypted_message
while True:
command = input("Enter 'e' to encrypt or 'd' to decrypt (or 'q' to quit): ")
if command.lower() == 'q':
break
if command.lower() not in ['e', 'd']:
print("Invalid command. Please try again.")
continue
message = input("Enter the message: ")
key = int(input("Enter the key (0-25): "))
if command.lower() == 'e':
encrypted_message = encrypt(message, key)
print("Encrypted message:", encrypted_message)
else:
decrypted_message = decrypt(message, key)
print("Decrypted message:", decrypted_message)
在上面的程序中,用户可以选择加密或解密操作。输入'e'表示加密,输入'd'表示解密,输入'q'表示退出程序。用户需要提供要加密或解密的消息和一个密钥(0到25之间的整数)。
这个程序使用了一个简单的凯撒密码算法,通过将字母的ASCII码加上密钥(对于加密操作)或减去密钥(对于解密操作),然后将结果转换回字符来实现加密和解密。非字母字符保持不变。
以下是程序的示例运行:
Enter 'e' to encrypt or 'd' to decrypt (or 'q' to quit): e Enter the message: Hello World! Enter the key (0-25): 3 Encrypted message: Khoor Zruog! Enter 'e' to encrypt or 'd' to decrypt (or 'q' to quit): d Enter the message: Khoor Zruog! Enter the key (0-25): 3 Decrypted message: Hello World! Enter 'e' to encrypt or 'd' to decrypt (or 'q' to quit): q
在 个例子中,用户选择加密操作,输入消息"Hello World!"和密钥3。程序输出了加密后的消息"Khoor Zruog!"。在第二个例子中,用户选择解密操作,输入加密后的消息"Khoor Zruog!"和密钥3。程序输出了解密后的消息"Hello World!"。最后,在第三个例子中用户选择退出程序。
