如果语句始终为真字符串

问题描述

我这里有一个相当简单的石头,剪刀,剪刀程序,在使用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,scissors GO! ')
player = player.lower()

if 'rock' or 'paper' or 'scissors' not in player:
    print("That is not how you play rock,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! ',sep ='')
    if player == 'scissors' and com_sel == 'paper':
        print('You win! ',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.',sep = '')
    if player == 'scissors' and com_sel == 'rock':
        print('You lose.',sep = '')```

解决方法

if中的条件是错误的。

考虑if语句并加上括号:

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

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

您需要交换条件的操作数

if player not in computer:

此交换之后,此行变得无关紧要(并且其条件也错误),您需要将其删除:

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

使用Python的运算符优先级(它们适用的顺序)查看此页面:

https://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.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','scissors'}:
    print("That is not how you play rock,paper,scissors!")
...