函数和方法以及str或return issu

2024-10-02 18:22:46 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个程序,需要一个描述,密码和密钥。但是当我将密码和密钥放入encrypt方法时,由于它是一个函数,当我尝试获取返回时会出现错误,那么我该如何绕过这个问题呢?你知道吗

def encrypt(plaintext, key):
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-"
cipher = " "
for c in plaintext:
    if c in alphabet:
        cipher += alphabet[(alphabet.index(c) + key) % (len(alphabet))]
print("Your encrypeted msg is: ", cipher)
return cipher


def decrypt(cryptedtext, key):
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-"
cipher = " "

for c in cryptedtext:
    if c in alphabet:
        cipher += alphabet[(alphabet.index(c) - key) % len(alphabet)]
print("decrypt: ", cipher)


def EnterInfo():
entry = input(" please enter in des to be stored")
entry2 = input(" please enter in pass to be stored")
entry3 = int(input(" please enter in key to be stored"))
encrypt(entry2, entry3)
entry2 = encrypt
with open("test.txt", 'a') as myfile:
    myfile.write(entry + ":" + entry2 + ":\n")

EnterInfo()

错误:

File "C:/Users/yoyo/PycharmProjects/crypt/CombineCryptAndTxtPyFile.py", line 29, in EnterInfo
myfile.write(entry + ":" + entry2 + ":\n")
TypeError: Can't convert 'function' object to str implicitly

Tags: tokeyininputdefbeencryptcipher
1条回答
网友
1楼 · 发布于 2024-10-02 18:22:46

你对函数用法处理不当:

encrypt(entry2, entry3)
entry2 = encrypt

在第一行中,调用entry2entry3上的encrypt函数,它返回结果,然后立即丢弃,因为您没有将它赋给任何对象。你知道吗

然后在第二行中,将entry2设置为函数encrypt,而不是上一个函数调用的结果。因此,您试图连接一个字符串和一个没有等效字符串的函数。你知道吗

相反,将encrypt调用的结果赋给一个变量,并在write调用中使用该结果。你知道吗

示例:

result = encrypt(entry1, entry2)

相关问题 更多 >