我需要使用 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/