【问题标题】:if, elif & !=, == boolean operations only return "false" with inputsif, elif & !=, == 布尔运算仅返回带有输入的“false”
【发布时间】:2020-10-23 03:47:44
【问题描述】:

我正在创建我们中间的 ripoff(为了好玩!),而 while True 和 if/elif/else 语句将只返回 false(不是冒名顶替者)与输入。我已经为名字创建了一个列表,列表中的 2 个随机元素将被选为 An Impostor。但是,每当我输入一个名为 The Impostor 的名字时,它只会返回

(玩家)不是冒名顶替者。

这是我的代码;

import sys, time, random
names = ["player1", "player2", "player3", "player4", "player5", "player6", "player7", "player8", "player9", "player10"]
print("Players: ")
for x in names:
  print(x)
print('—————————————————————————')
impostor1 = random.choice(names)
impostor2 = random.choice(names)
crewmates = 8
impostors = 2
tries = 6
while True:
  talk = input("Guess who The Impostor(s) are. " + str(crewmates) + " Crewmates are left. " + str(impostors) + " Impostors are left. You have " + str(tries) + " tries left.")
  if talk in names:
    print(talk + " was voted for.")
    time.sleep(0.1)
    if talk != impostor1 or talk != impostor2:
      notimp = talk + " was not An Impostor. "
      names.remove(talk)
      for y in notimp:
        sys.stdout.write(y)
        sys.stdout.flush()
        time.sleep(0.05)
      crewmates -= 1
      tries -= 1
    elif talk == impostor1 or talk == impostor2:
      wasimp = talk + " was An Impostor. "
      names.remove(talk)
      for v in wasimp:
        sys.stdout.write(v)
        sys.stdout.flush()
        time.sleep(0.1)
      impostors -= 1
  else:
    print("That player was either ejected or is not a valid player.")

但是,每当我将 Impostor 放入输入时,它就会说它不是 An Impostor?

【问题讨论】:

  • 哦,如果您需要更干净的代码版本,我可以提供。我只需要知道我对这些 if 语句做错了什么,我不需要重写代码。
  • 请提供预期的MRE。显示中间结果与预期结果的偏差。我们应该能够将您的代码块粘贴到文件中,运行它并重现您的问题。您为一个 3 行问题发布了 30 行代码。

标签: python if-statement variables input boolean


【解决方案1】:

我认为这行是问题的根源:

if talk != impostor1 or talk != impostor2:

假设impostor1 是player1 和impostor2 是player2 和player1 中的某人input,根据Python Boolean 表达式运算符or if 语句将计算如下:

if player1 != impostor1 计算为 False,因为 player1 确实等于 impostor1

到目前为止一切顺利,但是因为第一个测试是False,Python 只计算并返回右侧操作数,它可能是TrueFalse。在您的情况下,Python 将评估 if talk != impostor2 并返回 True,然后执行嵌套块。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 2015-10-17
    • 2012-12-06
    • 1970-01-01
    • 2015-01-07
    相关资源
    最近更新 更多