2012-11-17 59 views
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中給出的多個單詞。我想不通爲什麼^不起作用,但這:如何識別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' 

任何幫助將不勝感激,非常感謝

回答

2

您可以使用內置的功能any()

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

這裏涉及兩個問題:

  1. 非空字符串本身truthy
  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") 
+0

最後一個是你真正需要的。 – Keith

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' 
+1

複製大量代碼,除非您想爲每個操作使用不同的消息。回答你自己的問題並接受它,因爲解決方案是可疑的,特別是當有其他現有的解決方案時。 – BoppreH

+1

@BoppreH你說得對,我的代碼在這裏不是很乾。對於查看此問題的任何人,請勿使用我的代碼,請使用接受的答案。 – ntoscano