Python:将Casear密码和列式转置密码的加密输出写入.txt fi

2024-04-30 03:43:07 发布

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

我希望这是非常简单的修复。我在使用Python的Windows Powershell中遇到的错误如下:

回溯(最近调用最后一次):文件“[文件名.py]“,第66行,英寸 主(密文)名称错误:未定义名称“密文”

我的代码:

def main():
# cipherOne contains encrypted Cesear cipher
 myMessage = cipherOne
 ciphertext = encryptMessage(key, myMessage)

 # Print the encrypted string in ciphertext to the screen, with
 # a | (called "pipe" character) after it in case there are spaces at
 # the end of the encrypted message.
 print(ciphertext)

def encryptMessage(key, message):
 # Each string in ciphertext represents a column in the grid.
 ciphertext = [''] * key

 # Loop through each column in ciphertext.
 for col in range(key):
     pointer = col

     # Keep looping until pointer goes past the length of the message.
     while pointer < len(message):
         # Place the character at pointer in message at the end of the
         # current column in the ciphertext list.
         ciphertext[col] += message[pointer]

         # move pointer over
         pointer += key

 # Convert the ciphertext list into a single string value and return it.
 return ''.join(ciphertext)

 # call main() function.

 if __name__ == '__main__':
  main()

 target = open (filenamenew, 'a')

 target.write(ciphertext) #the error

 target.close()

我可以用密文将加密字符串打印到屏幕上,但无法解决如何克服这个错误,在这个错误中,我可以将密文附加到.txt文件中。在


Tags: ofthekeyinmessagestringmain错误
2条回答

按照RobertB的建议,将密文返回到main例程解决了这个问题。在

罗伯特布是正确的。以下是正确的代码修复:

只需将行“main()”更改为“cipheText=main()”,代码就可以工作了。函数已经返回文本;您现在只是通过不分配任何变量来获取返回值而丢弃它。

相关问题 更多 >