【问题标题】:raw_input() with "if....in.." statementsraw_input() 带有“if....in..”语句
【发布时间】:2014-12-08 22:35:28
【问题描述】:

我正在尝试编写一个需要用户输入的小游戏。

while True:
    x = raw_input("\n> ")

    if x in ["Susan", "Foreman"] and not grand_name: 
        print "The button glows! You have guessed the password! You can press the button now"
        grand_name = True
    elif x in ["Press", "press", "button"] and not grand_name:
        print "You have to guess the password first!"
    elif x in ["Press", "press", "button"] and grand_name:
        print "The TARDIS materializes around the Doctor! He has been freed from a gaseous monster!"
        end()
    else:
        print "Try Again."

我想让用户可以键入“按下按钮”或“我按下按钮”来满足所需的 elif 语句,而不是必须准确地键入列表的对象。如果单词本身在输入中的任何位置,我只想运行该语句。有没有一种方法可以让 Python 识别输入是否包含列表中的单词而无需准确输入单词?我希望这是有道理的。这是我问的第一个问题,所以我还在学习。谢谢。

我尝试使用如下示例中的 any(),但它返回错误“未定义全局名称 w”

当真时: x = raw_input("\n> ") opt1 = [“苏珊”,“工头”] opt2 = ["按下", "按下", "按钮"]

    if any(z in x for z in opt1): 
        print "The button glows! You have guessed the password! You can press the button now"
        grand_name = True
    elif any(w in x for w in opt2) and not grand_name:
        print "You have to guess the password first!"
    elif any(w in x for x in opt2) and grand_name:
        print "The TARDIS materializes around the Doctor! He has been freed from a gaseous monster!"
        end()
    else:
        print "Try Again."

【问题讨论】:

标签: python if-statement plist raw-input


【解决方案1】:

你是说if "press" in x.lower() or "button" in x.lower()

>>> "press" in "some sentence with the word press in it"
True

>>> words = ["press","button","otherword"]
>>> any(w in "aaa press bbb" for w in words)
True
>>> any(w in "aaa button bbb" for w in words)
True
>>> any(w in "aaa bbb" for w in words)
False

【讨论】:

  • 所以对于多个单词我只会使用一堆“或”语句?
  • 是的,或者将它们放在一个列表中并使用循环/列表理解。我用一个例子更新了代码。
  • 我这样做了,但收到一条错误消息,提示“未定义全局名称 w”。这太令人沮丧了。
  • 你的python版本是多少?试试any([w in "aaa bbb" for w in words])(带括号)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-06
  • 1970-01-01
  • 2014-12-12
  • 1970-01-01
  • 2017-08-14
相关资源
最近更新 更多