我直接从我的教科书中复制了这个块并得到了许多错误消息,但我没有能够解决这些问题。我已阅读并重读了我的书中的部分,据我所知,它只是一个块,所以我很困惑为什么会出现意外的缩进。我将在我的块下方发布我正在努力解决的错误。
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
答案 0 :(得分:2)
代码似乎很好,但是当我将代码复制到交互式Python shell中时,我可以重现您的问题。原因是当有一个空行时,Python shell会将其解释为当前代码块的结尾。因此,它尝试在函数的任何“主体”(因此def
错误)之前解释expected an indented block
行,然后在没有def
的情况下缩进主体的不同块(因此多个unexpected indent
错误。
要解决此问题,您有两种可能性:
python filename.py
执行该文件,或者启动交互式Python shell并使用from filename import archimedes
导入该函数。