【问题标题】:New and stuck on IndentationError: expected an indented block [duplicate]新的并卡在 IndentationError 上:预期缩进块 [重复]
【发布时间】:2018-04-20 07:00:57
【问题描述】:

我是 Python 和一般编程的新手。我正在努力为夏季学期的大学抢先一步。我正在尝试从这本初学者的书中学习,它完全按照我的说法引用了以下代码......我尝试以各种方式更改空格缩进,但我仍然收到此消息。我知道我可能在这里遗漏了一些东西,但我会很感激关于我应该如何进行的建议。

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)]


  >>> # Ghost Game
   ... from random import randint
   >>> print('Ghost Game')
   Ghost Game
   >>> feeling_brave = True
   >>> score = 0
   >>> while feeling_brave:
   ... ghost_door = randint(1, 3)
    File "<stdin>", line 2
    ghost_door = randint(1, 3)
             ^
   IndentationError: expected an indented block
    >>> ghost_door= randint(1, 3)
    >>> while feeling_brave:
    ... ghost_door= randint(1, 3)
    File "<stdin>", line 2
    ghost_door= randint(1, 3)
             ^
IndentationError: expected an indented block
>>> while feeling_brave:
... ghost_door = randint(1, 3)
  File "<stdin>", line 2
    ghost_door = randint(1, 3)
             ^
    IndentationError: expected an indented block
    >>> while feeling_brave:
    ... ghost_door = randint(1,3)
    File "<stdin>", line 2
       ghost_door = randint(1,3)
             ^
   IndentationError: expected an indented block
   >>> while feeling_brave:
   ... ghost_door =randint(1,3)
     File "<stdin>", line 2
    ghost_door =randint(1,3)

【问题讨论】:

  • 听起来不言自明,修复你的缩进(如果你不知道怎么做,谷歌会知道)
  • 所有你需要做的就是缩进ghost_door。就像错误所说的那样
  • 那么,据我所知,我在“g”之前缩进了吗?对不起,我还在努力理解布局..
  • @Joseph 这可能会对您有所帮助——这是 python 代码的样式指南python.org/dev/peps/pep-0008
  • 非常感谢英镑。

标签: python python-3.x error-handling indentation


【解决方案1】:

通过在行上现有缩进前面按 [TAB] 来添加缩进

... ghost_door = randint(1,3)

目前,您有:

while feeling_brave:
    ghost_door = randint(1, 3)

您没有将循环的“语句”作为缩进,因此解释器将其视为两个连续的命令。然而,拥有

while feeling_brave:
    ghost_door = randint(1, 3)

告诉解释器在循环运行时执行你的第二行。

【讨论】:

  • 将代码格式缩进四个空格,而不是使用 bsckticks,以保留新行。
  • @TZHX 保留新行是什么意思?
  • 如果您查看答案,代码是否与您预期的一样?
  • 嗯,不。好点子。感谢您的提醒;)
【解决方案2】:

在“while”语句之后,解释器会显示“...”。您必须通过在下一行的开头键入四个空格来提供缩进。

【讨论】:

  • 为什么要四个空格?
  • @TZHX 因为这相当于缩进。
  • 单个空格也是如此。或者一个标签。
  • 通常,一个制表符长达四个空格,但可以,任何空格都可以是缩进,只要保持一致即可。
猜你喜欢
  • 2021-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-15
  • 1970-01-01
  • 2021-11-24
相关资源
最近更新 更多