Search code examples
pythonchrord

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


I am able to encode the message using the ASCII table but unfortunately I am unable to decode the message. After the user the gets the result he/she will type either yes or no to redo the message to the original input. Thanks!

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

Solution

  • You should store the encoded message after the user provides it and you encode it with ord:

    message = input("Please input the message you want to encode: ")
    encoded = "".join([ord(ch) for ch in message])
    

    The next problematic line is this:

    plainText = plainText + chr(message)
    

    This tries to decode the entire message with chr on every iteration. It causes an error message:

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

    Instead of chr(message) it should be chr(ch), so it decodes each character separately. You can also do it more efficiently with "".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()
    

    Also note that variable names should be snake case in Python