为了账号安全,请及时绑定邮箱和手机立即绑定

if, elif & !=, == 布尔运算仅在输入时返回“false”

if, elif & !=, == 布尔运算仅在输入时返回“false”

慕容708150 2023-12-29 15:04:37
我正在创建一个“我们之中”的盗版(为了好玩!),而 while True 和 if/elif/else 语句只会返回 false(不是冒名顶替者)的输入。我创建了一个姓名列表,列表中的 2 个随机元素将被选为An Impostor。但是,每当我输入The Impostor的名称时,它只会返回(玩家)不是冒名顶替者。这是我的代码;import sys, time, randomnames = ["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 = 8impostors = 2tries = 6while 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.")但是,每当我将冒名顶替者放入输入中时,它都会说它不是冒名顶替者?
查看完整描述

1 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

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

if talk != impostor1 or talk != impostor2:

假设impostor1isplayer1 和impostor2isplayer2 以及inputplayer1中的某个人,根据PythonBoolean表达式运算符,orif语句的计算结果如下:

if player1 != impostor1评估为False因为player1 确实等于impostor1

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


查看完整回答
反对 回复 2023-12-29
  • 1 回答
  • 0 关注
  • 87 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信