2016-05-12 27 views
-1

試圖編寫一個python代碼來加密字符串。Python列表中的IndentationError

對字符串進行加密並且輸出是一個加密字符串。

print "Enter the string " 
a=raw_input() 
e='' 
i=0 
while i<len(a): 
    c='' 
    c+=a[i] 
    f=ord(c) 
    if i%3==0: 
    if f>21: 
     e+=chr(f-21) 
    else: 
     e+=chr(f+5) 
    elif i%3==1: 
    if ord(c)>24: 
     e+=chr(f-24) 
    else: 
     e+=chr(f+2) 
    else: 
    if ord(c)>21: 
     e+=chr(f-20) 
    else: 
     e+=chr(f+6)  


    i=i+1 
    del c 

print e 

但是,當運行此腳本時,出現錯誤。

e+=chr(f-24) 
     ^
IndentationError: unindent does not match any outer indentation level 
+5

您可以用空格混合選項卡。 –

+1

它適合我。把你在這裏得到的東西複製粘貼回你的腳本中。 –

+0

你可以完全刪除'c'並直接寫'f = ord(a [i])' – Daniel

回答

0

此縮進錯誤是由於您的腳本中混合了製表符和空格。解決方法是遍歷此文件中的每一行,確保爲每個縮進級別使用四個空格。看起來你現在只使用兩個空格,所以我不確定你是如何在這個位置結束的,但是刪除所有縮進並使用四個空格而不是製表符應該可以解決你的問題。

儘量讓你的代碼看起來更像是這個,看看您是否仍然有這些問題:

while i<len(a): 
    c='' 
    c+=a[i] 
    f=ord(c) 
    if i%3==0: 
     if f>21: 

請注意有四個空格,而不是兩個縮進的每個級別。這意味着c=''行在while語句的右側有四個空格。此外,if f>21行在if i%3==0的右邊有四個空格,在while語句的右邊有八個空格,因爲它是while語句下的兩個縮進級別。

0

我清理你的代碼:

plaintext = raw_input("Enter the string ") 
encrypted = '' 
for index, char in enumerate(plaintext): 
    char_code = ord(char) 
    index_mod = index % 3 
    if index_mod == 0: 
     if char_code > 21: 
      offset = -21 
     else: 
      offset = 5 
    elif index_mod == 1: 
     if char_code > 24: 
      offset = -24 
     else: 
      offset = 2 
    else: 
     if char_code > 21: 
      offset = -20 
     else: 
      offset = 6 
    encrypted += chr(char_code + offset) 

print encrypted 

爲了好玩,它也可以做這樣的:

offsets = [{True: -21, False: 5}, {True: -24, False: 2}, {True: -20, False: 6}] 
upper_limits = [21, 24, 21] 

plaintext = raw_input("Enter the string ") 
encrypted = '' 
for index, char in enumerate(plaintext): 
    char_code = ord(char) 
    index_mod = index % 3 
    offset = offsets[index_mod][char_code > upper_limits[index_mod]] 
    encrypted += chr(char_code + offset) 

print encrypted 

你甚至可以有

offsets = [[5, -21], [2, -24], [6, -20]] 

但它不太清楚那裏發生了什麼事。

但是現在,我看到偏移的圖案(第二永遠是第一負26),應在代碼來完成:

offsets = [5, 2, 6] 
upper_limits = [21, 24, 21] 

plaintext = raw_input("Enter the string ") 
encrypted = '' 
for index, char in enumerate(plaintext): 
    char_code = ord(char) 
    index_mod = index % 3 
    offset = offsets[index_mod] 
    if char_code > upper_limits[index_mod]: 
     offset -= 26 
    encrypted += chr(char_code + offset) 

print encrypted 
+3

這是否有幫助,這不是問題的答案。 –

+0

錯誤'行21,在加密+ = char(char_code +偏移量) TypeError:'str'對象不可調用' –

+0

@ShubhamChahal對不起,發了一個錯字(char而不是chr)。固定。 –