【问题标题】:Expected indented block in Python [duplicate]Python中预期的缩进块[重复]
【发布时间】:2014-12-15 19:36:55
【问题描述】:

我是 Python 的新手,对于程序的以下部分:

while g != s and t < 8:
g = input("What is your guess? ")
if g < s:
    print ("Too low...")
    elif g > s:
        print ("Too high...")
        t = t + 1

我得到错误:

expected indented block

这是为什么呢?还有,这个问题怎么解决?

谢谢。

【问题讨论】:

  • 那条线本身不是问题。请向我们展示周围的代码。您的一行或多行需要缩进。
  • @iCodez 感谢您的回复。我已经添加了环境

标签: python runtime-error block


【解决方案1】:

python 基于空格...您需要缩进块中的任何内容(在其他语言中,它们使用花括号)

while g != s and t < 8: #indented 0 spaces
    #every thing below is part of this block so it needs to be indented
    g = input("What is your guess? ") #indented 4
    if g < s: #indented 4 spaces
        #this happens when its too low (one line indented)
        print ("Too low...") #indented 8 spaces
    elif g > s:  #indented 4 spaces
        #this happens when its too high(one line indented)
        print ("Too high...") #indented 8 spaces
    # this always happens for every iteration of the loop
    t = t + 1 #indented 4 spaces

【讨论】:

  • 感谢您的回复。抱歉,我是Python 的新手,请您稍微澄清一下。我没有注意到您的解决方案中的差异
  • 我仍然有同样的错误。只是new lines吗? indent 在 Python 中是什么意思?有没有您推荐的自动执行此操作的编辑器?谢谢
  • 不要混合制表符和空格...使用任何显示空格/vs制表符的编辑器...缩进表示缩进级别(必须排列多少缩进)...我对其进行了编辑以明确说明如何许多空格缩进
【解决方案2】:

(正如 Joran Beasley 所说)问题可能是某些行使用空格缩进,而其他行使用制表符缩进。也有可能是某些行被 troll 缩进了。

为了确定,请在编辑器中打开“显示空白字符”,这样您就可以看到哪些行使用制表符进行缩进,哪些行使用空格进行缩进。

然后,要解决问题,请选择一个选项卡或空格,用它替换另一个,并坚持使用您选择的那个(最好是终生,或者直到您必须与对方的开发人员合作风格)。

Python 不介意您使用哪个(制表符或空格),只要您选择一个并在源文件的持续时间内坚持使用它。

this line is not indented
    this line is indented

【讨论】:

    猜你喜欢
    • 2017-09-19
    • 2021-07-12
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多