Python input correcct type and input but gives error with or without correct input
Question:
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 pappern")
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
Answers:
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'}:
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 pappern")
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
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'}: