-2

在我的 python 程序中,有时在我的 if 语句中只有最上面的一个有效

这是我的程序 http://ubuntuone.com/0u2NxROueIm9oLW9uQVXra

当你运行程序时,如果你去东西南北,然后它不起作用,问题出在功能室4()中:

def room4():
    """Forest go south to small town room 1 and east to forest path room8"""
    room = 4
    print "Forest you can go south to small town, east to forest path, or continue to explore the forest"
    cmd = raw_input('> ') 
    cmd = cmd.lower()
    if cmd == "e" or cmd == "east" or "go east":
        print room8()
    if cmd == "s" or cmd == "south" or "go south":
        print room1()
    if cmd == "forest" or cmd == "explore" or cmd == "explore forest" or cmd == "explore the forest":
        print room13()
    else:
        print error()
        print room4()
4

1 回答 1

5

将来,请包含您问题中的相关代码。我认为您指的是以下内容:

if cmd == "e" or cmd == "east" or "go east":
    print room8()
if cmd == "s" or cmd == "south" or "go south":
    print room1()
if cmd == "forest" or cmd == "explore" or cmd == "explore forest" or cmd == "explore the forest":
    print room13()
else:
    print error()
    print room4()

您将始终输入第一个if语句的原因是您有or "go east"而不是or cmd == "go east". 布尔上下文(如语句)中的字符串if评估为真。

而不是if cmd == "e" or cmd == "east" or cmd == "go east",您可以使用以下内容:

if cmd in {"e", "east", "go east"}:
    ...

如果您在 Python 2.6 或更低版本中不存在集合文字,请不要{"e", "east", "go east"}使用set(("e", "east", "go east")).

于 2013-01-08T17:41:14.593 回答