【问题标题】:Python Adventure Game -> Chose A or B in a while loop not working!Python 冒险游戏 -> 在 while 循环中选择 A 或 B 不起作用!
【发布时间】:2011-07-12 23:54:07
【问题描述】:

我正在尝试用 Python 创建一个简单的冒险游戏。我已经到了需要询问用户是否希望选择选项 A 或 B 并且正在使用 while 循环尝试执行此操作的地步:

AB = input("A or B?")

while AB != "A" or "a" or "B" or "b":
    input("Choose either A or B")

if AB == "A" or "a":
    print("A")
elif AB == "B" or "b":
    print("B")

问题是,无论您输入什么,都会出现“选择 A 或 B”的问题。我做错了什么?

【问题讨论】:

  • 你能修复代码中的缩进吗?现在这只是无效代码。

标签: python loops if-statement while-loop


【解决方案1】:

您的while 语句正在评估条件or,这对于您提供的字符串始终是正确的。

while AB != "A" or "a" or "B" or "b":

意思是:

while (AB != "A") or "a" or "B" or "b":

非空字符串始终为 True,因此写入 or "B" 将始终为 true,并且始终要求输入。最好写:

while AB.lower() not in ('a','b'):

【讨论】:

  • 工作就像一个魅力。非常感谢!
【解决方案2】:

AB != "A" or "a" or "B" or "b" 应该 AB.upper() not in ('A','B')

【讨论】:

    【解决方案3】:
    AB != "A" or "a" or "B" or "b"
    

    被解释为

    (AB != "A") or ("a") or ("B") or ("b")
    

    由于"a" 始终为true,因此此检查的结果将始终为true

    【讨论】:

    • /and since "A"/and since "a"/
    【解决方案4】:

    最好用:

    AB = raw_input("A or B?").upper()
    

    然后是其他人建议的not in 构造。

    【讨论】:

      【解决方案5】:

      改为使用raw_input() 函数,如下所示:

      ab = raw_input('Choose either A or B > ')
      while ab.lower() not in ('a', 'b'):
          ab = raw_input('Choose either A or B > ')
      

      input() 需要 Python 表达式作为输入;根据 Python 文档,它相当于eval(raw_input(prompt))。只需使用raw_input(),以及此处发布的其他建议。

      【讨论】:

      • 看起来他正在使用 Python 3,在这种情况下 input() 实际上是他需要使用的,如果我没记错的话。
      【解决方案6】:
      try:
          inp = raw_input    # Python 2.x
      except NameError:
          inp = input        # Python 3.x
      
      def chooseOneOf(msg, options, prompt=': '):
          if prompt:
              msg += prompt
          options = set([str(opt).lower() for opt in options])
          while True:
              i = inp(msg).strip().lower()
              if i in options:
                  return i
      
      ab = chooseOneOf('Choose either A or B', "ab")
      
      lr = chooseOneOf('Left or right', ('left','right'))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-30
        • 2016-01-08
        • 2022-11-04
        相关资源
        最近更新 更多