Python中的Elif语法错误

时间:2014-08-19 18:38:57

标签: python

这是我在Python中使用的基于文本的冒险游戏的if / elif / else条件的代码。本节的目的是为玩家提供选项,但是它说我所有“elif”语句的语法都有问题。

if command.lower() in ["north", "n"]:
    #With invitation
    if "invitation" in items:
        castle()
    #Without 'Invitation'   
    else:
        print "As you walk towards the gate, a guard approaches you and pushes you away. \"Sorry, pal,\" says the guard,\"You can't get in the castle without a written invitation from the king\""
        town_center()


elif command.lower() in ["east", "e"]:

    #market()

elif command.lower() in ["south", "s"]:

    #forest()

elif command.lower() in ["west", "w"]:

    #village()

elif command.lower() in ["inventory", "i"]:

    print items
    town_center()

elif command.lower() in ["look", "l"]:

    print "\nYou are standing in the center of the rural town of Grifiinhorn, a quaint rural town in the province of Bedrin. To the north, you see a giant castle sitting on top of a hill. To the east is the marketplace, and to the west is the village. To the south is exit gates of the town which faces the Dark Forest.\n" 
    town_center()

else:
    town_center()

我总是收到这个错误:

elif command.lower() in ["east", "e"]:
   ^
SyntaxError: invalid syntax

1 个答案:

答案 0 :(得分:3)

编辑:虽然这也是错误的,但这不是他的SyntaxError的原因

代码块中必须有某些。因为你评论了一些内容:

elif command.lower() in ["south", "s"]:

    #forest()

elif command.lower() in ["west", "w"]:

在第一个elif:之后的块中没有代码,因此当找到下一个elif:时会出现语法错误。

在您注释掉的块中添加pass语句:

elif command.lower() in ["south", "s"]:
    #forest()
    pass
elif command.lower() in ["west", "w"]:

pass什么都不做,但在这种情况下它可以形成一个块。