Python 凯撒密码加密
我需要用python、hacker和wow这三个词编写一个加密文本,并且在python中使用凯撒密码(不包括使用原始输入)的距离为3。这是我到目前为止所得到的,但我一直收到一条错误消息,我不知道如何修复它Python 凯撒密码加密,python,encryption,Python,Encryption,我需要用python、hacker和wow这三个词编写一个加密文本,并且在python中使用凯撒密码(不包括使用原始输入)的距离为3。这是我到目前为止所得到的,但我一直收到一条错误消息,我不知道如何修复它 >>> plainText = input("python: ") python: distance = int(input("3: ")) >>> code = "" >>> for ch in plainText:
>>> 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
您似乎是在交互式提示中输入此代码,而不是将其保存为文件并运行它。如果是这种情况,那么当您使用输入时,窗口将提示您输入,然后再允许您继续输入代码
plainText = input("python: ")
输入此行后,键入要加密的单词并按enter键。只有这样,你才能写这行:
distance = int(input("3: "))
在开始下一行之前,您应该输入所需的距离,代码=
作为一个风格提示,我建议将提示文本从python:和3:更改为类似于text to encrypt:和distance:,这样用户就可以清楚地知道应该输入什么
接下来,这里有一个缩进错误:
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)
行连续字符\后不应有空格。在任何情况下,最好只将整个表达式写在一行上,因为这一行的长度不足以保证分成两行。
第二个等号是打字错误。它应该是一个加号。
-
此时,您的程序应该运行时没有任何错误,但它还不会产生任何输出。加密每个字符时,将其添加到代码中。然后在循环结束后打印它
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将数字密码值转换为其等效字母
结果:
text to encrypt: hacker
distance: 13
unpxre
您的错误是for循环最后一行中的第二个赋值“=”。它必须是一个加号“+” 试试这个:
plainText = input("Enter text to encrypt: ")
distance = int(input("Enter number of offset: "))
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)
您只需要将ordValue从+1更改为+2您希望cipherValue=ord'a'=distance-ord'z'-ordValue+'是什么意思?因为这就是错误所在。老实说,我真的不确定,我是按照书中的例子做的。如果这是书中的文字代码,你有一本编辑不好的书。我想。。。那么我该如何解决这个问题呢?这条线似乎想要应用模运算;任何超出z的内容都应该添加到ord'a'中。cipherValue=ord'a'+cipherValue-ord'z'更有意义。
plainText = input("Enter text to encrypt: ")
distance = int(input("Enter number of offset: "))
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)