Python 练习中的缩进错误

IndentationError in a Python exercise

我是初学者,所以我确信这很普通。我正在进行初学者的练习,我正确地输入了代码并检查并重新检查了我输入的副本,但它看起来不像练习应该的样子。输出中应出现两行,但只出现了其中一行。我将在下面包括我在 Atom 中键入的内容以及代码的外观。我正在努力关注 "Learn Python the Hard Way",这是练习之一。我正在使用带有 Atom 的 Macbook 作为我的编辑器。注意到我完成的结果中只出现了一个句子吗?

我在Atom中输入的代码:

# A comment, this is so you can read your program later.
# Anything after the # is ignored by python.

print "I could have code like this." # and the coment after is ignored

# You can also use a comment to "disable" or comment out a piece of code:
 # print "This won't run."

 print "This will run."

如果编写得当,代码应该做什么:

$ python ex2.py
I could have code like this.
This will run.

这是我在终端机上看到的:

IndentationError: unexpected indent
Renays-MacBook-Pro:mystuff3 renayjohnson$ python ex2.py
  File "ex2.py", line 9
    print "This will run."
    ^
IndentationError: unexpected indent
Renays-MacBook-Pro:mystuff3 renayjohnson$ 

在第 9 行,print 行缩进了 space。只需删除 space 字符并重新运行您的脚本。另外,看看你练习的 original source ,那一行没有缩进。值得一提的是,注释行的缩进级别与它们后面的代码相同。在第 7 行的代码中,block comment 行也不应缩进,但它不会在该注释行中引发任何错误。

但是,您应该了解 Off-side rule 以及此类编程语言如何通过缩进来表达。