Python If语句

wil*_*wil -2 python

在我的python程序中,有时在我的if语句中只有顶部的一个有效

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

当你运行程序,如果你去东北西南,然后它不起作用问题是在函数room4():

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()
Run Code Online (Sandbox Code Playgroud)

And*_*ark 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()
Run Code Online (Sandbox Code Playgroud)

你总是输入第一个if陈述的原因是你有or "go east"而不是or cmd == "go east".布尔上下文中的字符串(如in if语句)评估为true.

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

if cmd in {"e", "east", "go east"}:
    ...
Run Code Online (Sandbox Code Playgroud)

如果你在Python 2.6或更低版本中,设置文字不存在,而不是{"e", "east", "go east"}使用set(("e", "east", "go east")).

  • 请注意,更好的方式进行这样的测试(有很多选项),而不是很多`或者`,如果在{"e","east","go east"}中的cmd:` . (2认同)