我正在尝试对凯撒密码进行编码,但是每次我尝试修复该错误时,它都将不起作用。似乎总是出现字符串或整数错误。 就我而言,所有的值都很好,没有可变的问题。我觉得问题出在我没有正确编写代码,但我不知道它是什么。
我的代码:
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'
答案 0 :(得分:0)
您收到的错误是由于您试图对int
和str
求和。
尤其是以下行:
key = input('What is the key: ')
即使str
包含数字,也会产生str
。
最简单的修改是将input()
的结果强制转换为int
,例如将该行替换为:
key = int(input('What is the key: '))
请注意,用于处理环绕的代码需要一个小的key
。如果您的key
是1000
,则您确实需要其他方法。通常,这可以使用modulo operation解决。