如何在raw_input中识别多个关键字?蟒蛇

时间:2012-11-17 23:15:35

标签: python raw-input

    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'

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

3 个答案:

答案 0 :(得分:2)

您可以使用内置函数any()

any(x not in action for x in  ("sneak","assasinate","stealth"))

答案 1 :(得分:2)

这里涉及两个问题:

  1. 非空字符串本质上是真实的
  2. or的关联性与您所写的有点不同。
  3. 最简单的方法是只使用第一个分支:

    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")
    

答案 2 :(得分: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'