Python 简单代码缩进的问题,如果,否则

problem with Python indentation with simple code, if, else

当我在输入 else: 后按回车键移动到下一行时,出现错误缩进,无论我如何对齐,我都尝试了 4 个空格,但仍然无法正常工作。我确保 else 与书中的 if 完全对齐,但仍然出错。

有人可以向我解释一下缩进是如何工作的吗?我正在使用 Python 2.7

代码:

if x%2 == 0:
    print "Even"
else: 
    print "Odd"
print "done with conditional"

在 Python 控制台中,使用正数空格或制表符时一切正常; 所以这些例子中的任何一个都可以工作:

if True:
 print('Hello')
else:
 print('Not hello')

if True:
    print('Hello')
else:
    print('Not hello')

if True:
        print('Hello')
else:
        print('Not hello')

编辑 要搜索问题出在哪里,请尝试 this answer;打电话

python -m tabnanny <your_script>.py

你会得到一个输出,告诉你哪一行有问题。

示例输出:

'test.py': Indentation Error: unindent does not match any outer indentation level (<tokenize>, line 12)

假设 python 具有像倒三角一样的反向层次结构。

  1. 当您想在第 1 级编写 function/loop/conditions 时,我们在第 2 级的这三个部分中编写我们正在编写的任何代码。

  2. 在您的代码中,"if" 和 "else" 属于第一级。所以不要在这些前面给出任何 spaces。

  3. print statements inside 'if' and 'else' should have same tab space or white space as they come under 2nd level.

  4. outer print 语句不会有 space 因为它又回到了第一层。

希望对您有所帮助