我直接从教科书中复制了这个 block ,并收到许多错误消息,但我无法解决其中的任何一个。我已经阅读并重读了我书中的这一部分,据我所知,这都是一个 block ,所以我很困惑为什么会有意外的缩进。我将在我的区 block 下面发布我正在努力解决的错误。
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
...以下是错误:
>>> 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
最佳答案
代码似乎没问题,但是当我将该代码复制到交互式 Python shell 中时,我可以重现您的问题。原因是当有空行时,Python shell 会将其解释为当前代码块的结尾。因此,它尝试在函数有任何“主体”之前解释 def
行(因此 预期缩进 block
错误),然后解释缩进的不同 block 正文没有 def
(因此出现多个意外缩进
错误)。
要修复它,您有两种可能性:
- 将代码复制到文本文件中并使用
python filename.py
执行该文件,或者启动交互式 Python shell 并使用from filename import archimedes
导入函数. - 或者删除函数主体中的所有空行,然后将其粘贴到交互式 shell 中。
关于indentation - 粘贴代码会产生多个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29722655/