Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

python - If Statement Always True (String)

I have here a rather simple rock, paper, scissors program where I am having some trouble with if statements. For some reason, when I enter rock, paper, or scissors (True Values), the program always performs

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

for some reason. The complete program is as below.


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 = '')```
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The conditions in if are wrong.

Consider the if statement with parentheses:

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

It will always return True because rock will always be true.

You need to swap conditions' operands

if player not in computer:

After this swap, this line becomes irrelevant (and also its conditions are wrong) You need to remove it:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...