If语句始终为True(字符串)



我有一个相当简单的石头、纸、剪刀程序,其中我在if语句方面遇到了一些问题。出于某种原因,当我输入石头、纸或剪刀(真值(时,程序总是执行

if 'rock' or 'paper' or 'scissors' not in player:
print("That is not how you play rock, paper, scissors!")

出于某种原因。完整的程序如下。


computer = ['rock', 'paper', 'scissors']
com_num = randint(0,2)
com_sel = computer[com_num]
player = input('Rock, paper, scissors GO! ')
player = player.lower()
if 'rock' or 'paper' or 'scissors' not in player:
print("That is not how you play rock, paper, scissors!")
if player == 'rock' or 'paper' or 'scissors':    
#win
if player == 'rock' and com_sel == 'scissors':
print('You win! ', player.title(), ' beats ', com_sel, '!', sep ='')
if player == "paper" and com_sel == "rock":
print('You win! ', player.title(), ' beats ', com_sel, '!', sep ='')
if player == 'scissors' and com_sel == 'paper':
print('You win! ', player.title(), ' beats ', com_sel, '!', sep ='')
#draw
if player == com_sel:
print('It's a draw!')

#lose
if player == 'rock' and com_sel == 'paper':
print('You lose.', com_sel.title(), "beats", player, '!', sep = '')
if player == 'paper' and com_sel == 'scissors':
print('You lose.', com_sel.title(), "beats", player, '!', sep = '')
if player == 'scissors' and com_sel == 'rock':
print('You lose.', com_sel.title(), "beats", player, '!', sep = '')```

if中的条件错误。

考虑带括号的if语句:

if ('rock') or ('paper') or ('scissors' not in player):

它将始终返回True,因为rock将始终为真。

您需要交换条件的操作数

if player not in computer:

在这个交换之后,这条线变得不相关(而且它的条件也是错误的(你需要删除它:

if player == 'rock' or 'paper' or 'scissors': 

看看这个页面,看看Python的运算符先例(它们应用的顺序(:

https://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_preduce.html

您可以看到not in列得比or高,这意味着它首先被评估。因此,您可以将if语句重写为:

if 'rock' or 'paper' or ('scissors' not in player): ...

现在我们看到,你真的有一个or,有三件事。字符串不是空的,因此第一个'rock'的计算结果已经为true,因此整个值始终为true。

要分解您的报表,

if 'rock' or 'paper' or 'scissors' not in player:

假设player = 'scissors'。这种情况将被评估为,

('rock'(或('paper'(或('scissors' not in player(

其再次评估为

True or True or False

因此,求值为True总是因为字符串(例如"rock"(求值为True而忽略其他字符串,因为OR(任何一个True都为True(。所以不管你在播放器里放什么都无关紧要。

正确条件

if player not in ['rock', 'paper', 'scissors']:

此语句检查player是否不在给定列表中。

if player not in {'rock', 'paper', 'scissors'}:
print("That is not how you play rock, paper, scissors!")
...

最新更新