Python 列表中的缩进错误[重复]

问题描述 投票:0回答:2

尝试编写Python代码来加密字符串。

对字符串进行加密,输出是加密后的字符串。

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   
python indentation
2个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.