错误消息:“预期缩进块”

时间:2012-08-26 18:50:43

标签: python

所以我正在尝试编写一个游戏,我正在尝试连接关卡的不同区域。这部分代码应该允许用户选择进入关卡但终端一直给我这个错误命令:"expected an indented block"

我试图用四个空格替换所有标签,反之亦然,但错误不会消失。

顺便说一下,我知道在定义一个函数之后,每一行后面会缩进四个空格或一个标签,但这是我的第一个问题,我无法弄清楚如何在这里做到这一点。


def entry_hall():   
    first = raw_input("Go upstairs\nGo forwards\nGo left\nLeave\n:")
    if first == "Go upstairs" or "upstairs":
        print "Walking up the stairs" 
        import Upstairs_hallway.py
    elif first == "Go forwards" or "forwards":
        pass
    elif first == "Go left" or "left":
        pass
    elif first == "Leave":
        print """
You're a cop. You are not a baby. Do something else
""" 
        #restart the script

entry_hall()

3 个答案:

答案 0 :(得分:1)

确保缩进是恒定的:

def entry_hall():   
    first = raw_input("Go upstairs\nGo forwards\nGo left\nLeave\n:")

    if first in ["Go upstairs", "upstairs"]:
        print "Walking up the stairs" 
        import Upstairs_hallway
    elif first == "Go forwards" or "forwards":
        pass
    elif first == "Go left" or "left":
        pass
    elif first == "Leave":
        print "You're a cop. You are not a baby. Do something else" 
        #restart the script

entry_hall()

此外,if first == "Go upstairs" or "upstairs"效果不佳。该声明将按以下方式进行评估:

if (first == "Go upstairs") or "upstairs"

第一个条件first == "Go upstairs"可以评估为TrueFalse,但第二个条件"upstairs"将始终评估为True。由于您还使用了or语句,因此您的第一个条件始终评估为True

使用列表可以解决此问题:

if first in ["Go upstairs", "upstairs"]:

此外,在Python中,import语句不希望有.py扩展名。只需提供文件名:

import Upstairs_hallway

答案 1 :(得分:0)

def之后的每行代码后再添加四个字符:

def entry_hall():   
    first = raw_input("Go upstairs\nGo forwards\nGo left\nLeave\n:")

答案 2 :(得分:0)

我不需要原来的答案,因为您说def语句的错误对齐是由于不知道如何在Markdown中正确粘贴它。

但您确实遇到了另一个问题:您的if语句错误。交换if s == 'first' or 'second': if s in ['first', 'second']: - 前者将永远为真,因为'second'的计算结果为真。