Search code examples
pythonpython-3.xpycharm

I am trying to make a caeser cipher in python (3.8), and there are constant errors coming up


I am trying to write a Ceaser cipher. As you can see below, an error comes up. However, from what I can tell, there should be no error.

The error is obvious happening at translatedIndex = symbolIndex + key, but that means either symbolIndex or key have the error. I am not sure which one it is, and I am not sure how I can fix this issue.

My code:

message = ''
mode = ''


print("Type what sort of function you would like. (NOTE: only lowercase, and the values of 'encrypt' and 'decrypt' are accepted)")

mode = input("What mode do you want: ")

message = input('What is the message you want to encrypt/decrypt: ')

key = input('What is the key: ')

SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'


translated = ''

for symbol in message:
    # Note: Only symbols in the `SYMBOLS` string can be encrypted/decrypted.
    if symbol in SYMBOLS:
        symbolIndex = SYMBOLS.find(symbol)

        # Perform encryption/decryption:
        if mode == 'encrypt':
            translatedIndex = symbolIndex + key
        elif mode == 'decrypt':
            translatedIndex = symbolIndex - key


        # Handle wrap-around, if needed:
        if translatedIndex >= len(SYMBOLS):
            translatedIndex = translatedIndex - len(SYMBOLS)
        elif translatedIndex < 0:
            translatedIndex = translatedIndex + len(SYMBOLS)

        translated = translated + SYMBOLS[translatedIndex]
    else:
        # Append the symbol without encrypting/decrypting:
        translated = translated + symbol

print(translated)

The error is:

Traceback (most recent call last):
  File "C:/Users/mghaf/Desktop/Coding/coding/My codes (cypher)/caesarCipher.py", line 27, in <module>
    translatedIndex = symbolIndex + key
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Solution

  • The error you are getting is due to the fact you are trying to sum a int and a str.

    In particular, the following line:

    key = input('What is the key: ')
    

    produces a str, even if the str contains numbers. The simplest modification is to just cast the result of input() to int, e.g. replacing that line with:

    key = int(input('What is the key: '))
    

    As a side note, your code for handling wrapping around requires a small key. If your key is, say, 1000 you do need a different approach. Typically, this is solved using the modulo operation.