2014-02-10 161 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)