Python ';int';和';str';哪里不应该';不是。。。?

Python ';int';和';str';哪里不应该';不是。。。?,python,python-3.x,dictionary,casting,Python,Python 3.x,Dictionary,Casting,我已经盯着下面的代码段看了很长一段时间了,但我仍然不明白为什么在第8行收到“TypeError:unsupported operation type for+:'int'和'str'”错误。有人能提出一个解决办法吗?起初,我甚至不认为我需要强制转换为str()或int(),但我已经尝试了几乎所有我能想到的方法。有人能帮忙吗 L2I = dict(zip("ABCDEFGHIJKLMNOPQRSTUVWXYZ",range(26))) I2L = dict(zip(range(26),"ABCDE

我已经盯着下面的代码段看了很长一段时间了,但我仍然不明白为什么在第8行收到“TypeError:unsupported operation type for+:'int'和'str'”错误。有人能提出一个解决办法吗?起初,我甚至不认为我需要强制转换为str()或int(),但我已经尝试了几乎所有我能想到的方法。有人能帮忙吗

L2I = dict(zip("ABCDEFGHIJKLMNOPQRSTUVWXYZ",range(26)))
I2L = dict(zip(range(26),"ABCDEFGHIJKLMNOPQRSTUVWXYZ"))

def encrypt(text, key):

        ciphertext = ''
        for c in text.upper():
                if c.isalpha(): ciphertext += str(I2L[ (int(L2I[c]) + key) % 26])
                else: ciphertext + c
        return ciphertext

def decrypt (ciphertext, key):

        plaintext = ''

        for c in ciphertext.upper(): 
                if c.isalpha(): plaintext2 += str(I2L[ (int(L2I[c]) - key) % 26])
                else: plaintext + c
        return plaintext


message = input('Enter plaintext: ')
key = input('Enter key value (1-25): ')

print ('Plaintext was: ', message)
print (encrypt(message, key))
print (decrypt(encrypt(message, key), key))
谢谢大家!

key=input(“输入键值(1-25):”)行调用
input()
返回一个
str
,即使用户传递了一个数字。因此,您的
不是预期的
int
,而是
str
。要避免它,请执行以下操作:

key = int(input("Enter a key value (1-25):" ))

请将您的问题包括导致错误的输入,以及完整的错误回溯问题在子表达式
int(L2I[c])+key
中。您正在尝试连接一个整数和一个字符串。第8行:有
int(L2I[c])+key
key
变量是字符串吗?看起来您的
key
输入从未从字符串转换为整数,因此当您将其添加到第8行时,会导致错误
key=input('Enter key value(1-25):')
。如果您查看
类型(键)
,它将是一个
str
。在将其传递给函数之前,可以将其强制转换为
int