我正在尝试在python(3.8)中创建caeser密码,并且不断出现错误

时间:2020-01-24 09:46:50

标签: python python-3.x pycharm

我正在尝试对凯撒密码进行编码,但是每次我尝试修复该错误时,它都将不起作用。似乎总是出现字符串或整数错误。 就我而言,所有的值都很好,没有可变的问题。我觉得问题出在我没有正确编写代码,但我不知道它是什么。

我的代码:

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)

显示的错误如下:

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'

1 个答案:

答案 0 :(得分:0)

您收到的错误是由于您试图对intstr求和。

尤其是以下行:

key = input('What is the key: ')
即使str包含数字,

也会产生str。 最简单的修改是将input()的结果强制转换为int,例如将该行替换为:

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

请注意,用于处理环绕的代码需要一个小的key。如果您的key1000,则您确实需要其他方法。通常,这可以使用modulo operation解决。