粘贴代码会产生多个错误

wat*_*age 2 indentation python-3.4

我直接从我的教科书中复制了这个块,并收到了许多错误消息,我无法解决这些错误消息。我已经阅读并重读了我的书的一部分,据我所知,它都是一个街区,所以我很困惑为什么会有意外的缩进。我将在我的区块下方发布我正在努力解决的错误。

import math

def archimedes (sides):

      innerangleB = 360.0 / sides
      halfangleA = innerangleB / 2

      onehalfsideS = math.sin(math.radians(halfangleA))

      sideS  =  onehalfsideS * 2

      polygonCircumference = sides * sideS

      polygonCircumference = sides * sideS
      pi = polygonCircumference/2

      return pi
Run Code Online (Sandbox Code Playgroud)

...这里是错误:

>>> import math
>>> 
>>> def archimedes (sides):
... 
  File "<stdin>", line 2

    ^
IndentationError: expected an indented block
>>>       innerangleB = 360.0 / sides
  File "<stdin>", line 1
    innerangleB = 360.0 / sides
    ^
IndentationError: unexpected indent
>>>       halfangleA = innerangleB / 2
  File "<stdin>", line 1
    halfangleA = innerangleB / 2
    ^
IndentationError: unexpected indent
>>> 
>>>       onehalfsideS = math.sin(math.radians(halfangleA))
  File "<stdin>", line 1
    onehalfsideS = math.sin(math.radians(halfangleA))
    ^
IndentationError: unexpected indent
>>> 
>>>       sideS  =  onehalfsideS * 2
  File "<stdin>", line 1
    sideS  =  onehalfsideS * 2
    ^
IndentationError: unexpected indent
>>> 
>>>       polygonCircumference = sides * sideS
  File "<stdin>", line 1
    polygonCircumference = sides * sideS
    ^
IndentationError: unexpected indent
>>> 
>>>       polygonCircumference = sides * sideS
  File "<stdin>", line 1
    polygonCircumference = sides * sideS
    ^
IndentationError: unexpected indent
>>>       pi = polygonCircumference/2
  File "<stdin>", line 1
    pi = polygonCircumference/2
    ^
IndentationError: unexpected indent
>>>    
...       return pi
Run Code Online (Sandbox Code Playgroud)

tob*_*s_k 5

代码似乎很好,但是当我将该代码复制到交互式 Python shell 时,我可以重现您的问题。原因是当出现空行时,Python shell 会将其解释为当前代码块的结尾。因此,它尝试def在函数存在任何“主体”之前解释该行(因此是expected an indented block错误),然后是没有 a 的缩进主体的不同块def(因此是多个unexpected indent错误)。

要修复它,您有两种可能性:

  • 或者,将代码复制到文本文件中并使用该文件执行该文件,python filename.py或者启动交互式 Python shell 并使用from filename import archimedes.
  • 或者删除函数体中的所有空行,然后将其粘贴到交互式 shell 中。