Code not working as expected to


#1



https://www.codecademy.com/en/courses/python-ext/projects/rock-paper-scissors


when I prompt user to make a choice and he prints something other than rock, paper or scissors, I expect the function to call again i.e prompt_user to come again. But it doesnt. instead it prints what user enters which shouldnt happen.


import random
from time import sleep

def prompt_user():
    user_choice= str(raw_input('Please choose from Rock, Paper or Scissors; You must choose only one '))
    user_choice= user_choice.upper()
    if user_choice == 'ROCK' or 'PAPER' or 'SCISSORS':
        print 'you choose ' + str(user_choice)
        return user_choice
    else:
        return prompt_user()

      
prompt_user()


#2

Turns out ,It always comes out to be true.

You have to separately define all the cases and use or to make a compound boolean expression..
like..

if user_choice == 'ROCK' or user_choice == 'Paper' and so on..

You can use in operator too but then you have to put these three options in a tuple or list.


#3

umm okay. But I didnt get why it will always come out to be true??


#4

I mean if I enter for instance 'ball'. It returns 'BALL'. While I expect it should call function again..


#5

Take an example..

x = 45
if x == 344 or 67:
    pass

due to operator precedence x == 344 is checked first and evaluates out to be False.
Then we have this..

False or 67

Non -zero values ( apart from 0)/Non empty data types (other than "" ,[] ,{}, () etc) are actually truthy values, it means as a expression it turns into True boolean value.

for example..

if "green":
    print 2
 # it prints 2

so False or 67 gives us 67 then as its non-zero value, It is a truthy value (True).
so your if test's always comes out to be true.

Operator precedence


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.