3
    if "sneak" or "assasinate" or "stealth" not in action:
        print"...cmon, you're a ninja! you can't just attack!"
        print "STEALTH, SNEAK ATTACKS, ASSASINATIONS!"
        print "The gods decide that you have come too close to loose now."
        print "they give you another chance"
        return 'woods'
    else:
        print "You throw a ninja star at a near by tree to distract the warlord,"
        print "you take out his legs, get him on the ground and have your blade to his neck"
        print "You take off his mask to stare into his eyes as he dies, and realise, it's your father."
        return 'the_choice'

这是我遇到问题的代码。我是 python 新手,我需要知道如何识别 raw_input 中给出的多个单词。我不知道为什么 ^ 不起作用,但这确实:

action = raw_input("> ")

if "body" in action:
    print "You hit him right in the heart like a pro!"
    print "in his last dying breath, he calls for help..."
    return 'death'

任何帮助将不胜感激,非常感谢

4

3 回答 3

2

您可以使用内置功能any()

any(x not in action for x in  ("sneak","assasinate","stealth"))
于 2012-11-17T23:19:07.403 回答
2

这里涉及两个问题:

  1. 非空字符串本质上是真实的
  2. 的关联性与or您所写的有点不同。

看到这一点的最简单方法是仅使用第一个分支:

if "sneak":
   print "This was Truthy!"

如果我们在 if 子句中添加括号,它将像这样解析(因为它从左到右读取:

if ("sneak" or "assasinate") or ("stealth" not in action)

@AshwiniChaudhary 的使用建议any是一个很好的建议,但要明确的是,它会产生与执行相同的结果:

"sneak" in action or "assasinate" in action or "stealth" in action

顺便说一句,如果你正在寻找一个完全匹配的,你也可以这样做

if action in ("sneak", "assasinate", "stealth")
于 2012-11-17T23:34:38.283 回答
0

感谢您的帮助,但我想通了,这就是我所做的:

    action = raw_input("> ")

    if "sneak" in action:
        print "You throw a ninja star at a near by tree to distract the warlord,"
        print "you take out his legs, get him on the ground and have your blade to his neck"
        print "You take off his mask to stare into his eyes as he dies, and realise, it's your father."
        return 'the_choice'
    elif "assasinate" in action:
        print "You throw a ninja star at a near by tree to distract the warlord,"
        print "you take out his legs, get him on the ground and have your blade to his neck"
        print "You take off his mask to stare into his eyes as he dies, and realise, it's your father."
        return 'the_choice'
    elif "stealth" in action:
        print "You throw a ninja star at a near by tree to distract the warlord,"
        print "you take out his legs, get him on the ground and have your blade to his neck"
        print "You take off his mask to stare into his eyes as he dies, and realise, it's your father."
        return 'the_choice'
    else:
        print"...cmon, you're a ninja! you can't just attack!"
        print "STEALTH, SNEAK ATTACKS, ASSASINATIONS!"
        print "The gods decide that you have come too close to loose now."
        print "they give you another chance"
        return 'woods'
于 2012-11-20T00:48:58.760 回答