如何使用 "chr" 和 "ord" 命令来破译用户输入的消息?

How can I use the "chr" and "ord" command to decipher a message that a user has input?

我可以使用 ASCII 对消息进行编码 table,但遗憾的是我无法解码消息。在用户获得结果后 he/she 将键入 yes 或 no 以将消息重做为原始输入。谢谢!

def main():

    message = input("Please input the message you want to encode: ")
    for ch in message:
        print(ord(ch))

    print()

    decode = input("Would you like to decode it? (Yes or No?): ")
    if decode == str('yes', 'Yes'):
        plainText = ""
        for ch in message:
            numCode = eval(decode)
            plainText = plainText + chr(message)
        print("Your decoded message is: ", plainText)


    else:
        print("Thank you for encrypting with us today!")



main()

您应该在用户提供后存储编码消息,并使用 ord:

对其进行编码
message = input("Please input the message you want to encode: ")
encoded = "".join([ord(ch) for ch in message])

下一行有问题的是:

plainText = plainText + chr(message)

这会尝试在每次迭代时用 chr 解码整个消息。它会导致错误消息:

>>> chr("abc")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required

而不是 chr(message) 应该是 chr(ch),所以它会分别解码每个字符。您还可以使用 "".join():

更有效地做到这一点
def main():

    message = input("Please input the message you want to encode: ")
    for ch in message:
        print(ord(ch))

    print()

    decode = input("Would you like to decode it? (Yes or No?): ")
    if decode == str('yes', 'Yes'):
        plain_text = "".join([chr(ch) for ch in encoded])
        print("Your decoded message is: ", plain_text)
    else:
        print("Thank you for encrypting with us today!")



main()

还要注意 Python

中的变量名应该是蛇形大小写