2014-02-10 71 views
1

我需要编写python,hacker和wow这两个词的加密文本,并且使用一个不包含raw_input的凯撒密码的距离为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 
+1

你想'的CipherValue = ORD( 'A')什么=距离 - (ORD( 'Z') - ordValue +“)'为*意味着*?因为那是错误的地方。 –

+0

我真的不确定,我是在书中的例子 – user3292818

+0

如果这是书中的文字代码,你有一本编辑不好的书。 –

回答

1

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

plainText = input("python: ") 

输入此行后,输入要加密的单词,然后按Enter键。只有这样,你写这行:

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

你开始的下一行,code = ""前应输入你想要的距离。

作为一种文体提示,我建议将提示文本从"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) 
  • 你不应该有续行符\之后的任何空间。无论如何,将整个表达式写在一行上可能会更好,因为该行不够长,不足以分解成两行。
  • 第二个等号是拼写错误。它应该是一个加号。

-

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 
0

你的错误是在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)