python-3.x 条件语句未与“or”运算符一起运行[duplicate]

b09cbbtk  于 2022-12-27  发布在  Python
关注(0)|答案(1)|浏览(131)
    • 此问题在此处已有答案**:

Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?(6个答案)
昨天关门了。
作为上下文,我做了一个简单的数字游戏,询问用户是否愿意玩,如果用户输入"Yes"或"yes",游戏就会开始,如果用户输入"No"或"no",游戏就会结束。
我从if/elif/else条件开始,但是我的 * 或 * 操作符不起作用,所以即使用户输入"no",它也会继续游戏并运行下一行代码。我做错了什么?
下面是我的代码:
'

if start_game == "Yes" or "yes" :
  print("Let's begin: ")
  print (random_number_one)
  input("Do you think the next number will be higher or lower? Type 'H' for higher or 'L' for lower:  ")
elif start_game == "No" or "no" :
  print("Okay, maybe next time.")
else:
  print("Invalid response. You lose.")

'
我不知道为什么它不能正确运行,我也没有收到任何错误。是否有其他问题?

q1qsirdb

q1qsirdb1#

使用以下代码:

if start_game == "Yes" or start_game == "yes" :
  print("Let's begin: ")
  print (random_number_one)
  input("Do you think the next number will be higher or lower? Type 'H' for higher or 'L' for lower:  ")
elif start_game == "No" or start_game == "no" :
  print("Okay, maybe next time.")
else:
  print("Invalid response. You lose.")

解释

Python的==运算符优先于or运算符,所以python将你的代码看作(start_game == "Yes") or ("yes")(start_game == "No") or ("no")
"yes"这样的字符串有一个真值,因此被解释为True
因此,当输入为"no"时,第一个条件的计算结果为(False) or (True),即True

可读性更强

if start_game in [ "Yes", "yes" ]:
  print("Let's begin: ")
  print (random_number_one)
  input("Do you think the next number will be higher or lower? Type 'H' for higher or 'L' for lower:  ")
elif start_game in [ "No", "no" ]:
  print("Okay, maybe next time.")
else:
  print("Invalid response. You lose.")

注意如何使用数组检查变量是否与多个值中的一个匹配。

相关问题