python - 凯撒密码加密

标签 python encryption

我需要使用 Python 中的凯撒密码(不包括使用 raw_input)编写单词 python、hacker 和 wow 的加密文本,并且距离为 3。这是我到目前为止所得到的,但我不断收到错误消息,并且我不知道如何修复它。

>>> plainText = input("python: ") 
python: distance = int(input("3: ")) 
>>> code = "" 
>>> for ch in plainText:    
        ordValue = ord(ch)  
        cipherValue = ordValue + distance   
        if cipherValue > ord('z'):      
        cipherValue = ord('a') = distance - \                 
        (ord('z') - ordValue + 1)        
SyntaxError: can't assign to function call

最佳答案

您似乎正在将此代码输入到交互式提示中,而不是将其保存为文件并运行它。如果是这种情况,那么当您使用input时,窗口会提示您输入,然后才允许您继续输入代码。

plainText = input("python: ") 

输入此行后,输入您要加密的单词并按 Enter 键。只有这样你才应该写下这一行:

distance = int(input("3: ")) 

您应该在开始下一行之前输入所需的距离,code = ""

作为风格提示,我建议将提示文本从 "python:""3:" 更改为“要加密的文本:”和“距离” : ",因此用户很清楚他应该输入什么。

<小时/>

接下来,这里有一个缩进错误:

    if cipherValue > ord('z'):      
    cipherValue = ord('a') = distance - \      

if 条件之后的行应进一步缩进一级。

    if cipherValue > ord('z'):      
        cipherValue = ord('a') = distance - \      
<小时/>

接下来,您在这些方面有两个问题。

    cipherValue = ord('a') = distance - \
    (ord('z') - ordValue + 1)
  • 行继续符 \ 后不应有任何空格。无论如何,最好将整个表达式写在一行上,因为该行的长度不足以保证分成两行。
  • 第二个等号是一个拼写错误。它应该是一个加号。

-

    cipherValue = ord('a') + distance - (ord('z') - ordValue + 1)
<小时/>

此时,您的程序应该可以正常运行,没有任何错误,但尚未产生任何输出。当您加密每个字符时,将其添加到 code 中。然后在循环结束后打印它。

plainText = input("text to encrypt: ") 
distance = int(input("distance: ")) 
code = "" 
for ch in plainText:    
    ordValue = ord(ch)  
    cipherValue = ordValue + distance   
    if cipherValue > ord('z'):      
        cipherValue = ord('a') + distance - (ord('z') - ordValue + 1)
    code = code + chr(cipherValue)
print(code)
#to do: write this to a file, or whatever else you want to do with it

这里,chr 将数字 cipherValue 转换为其等效的字母。

<小时/>

结果:

text to encrypt: hacker
distance: 13
unpxre

关于python - 凯撒密码加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21677347/

相关文章:

Python将元组压缩为第一个值

android - 优化密码(技术上)是什么意思? (Java中的AES案例)

java: Blowfish 加密解密 Bad padding 异常

Flask 的 Python 装饰器

python - Pandas:根据某些条件过滤 groupby 数据

encryption - 如何确定 zip 文件的加密方案

php - mcrypt 加密将 s 串 '%00' 添加到字符串末尾

php - 加密mysql数据并通过超链接,然后在下一页解密?

python - 如何修复谷歌地球引擎中的 "Manifests for TfRecord ingestion must have exactly one tileset with exactly one source"

Python Week Numbers,其中所有周都有 7 天,无论年份是否翻转