Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python input correcct type and input but gives error with or without correct input

def choicesChecker(userchoice):
if userchoice != 'r' or 'p' or 's':
    print('error')
    print(type(userInput))
else:
    print('correct input')

userInput = input("Pls input one of the following \n r for rock, \n s for siccors \n p for papper\n")

choicesChecker(userInput)

I am making a basic python rock paper scissors game and when i type r or p or s in the input and run my function it goes to the print error line but when i put anything else it gives the same print error line.

The print type also gives a string attribute so what is wrong there are no spaces in my input

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

userchoice != 'r' or 'p' or 's' is evaluated as (userchoice != 'r') or ('p') or ('s'). 'p' and 's' are both truthy as they are non-empty strings, so this whole expression is always True.

Instead, you should explicitly write out each comparison. In addition, you should use and since you want to check that the input is not equal to each of those strings.

if userchoice != 'r' and userchoice != 'p' and userchoice != 's':

This can also be simplified by checking for existence in a set:

if userchoice not in {*'rps'}:
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading