I’ve been working my way through Python, but can’t seem to get past string comparisons. I wrote a function that takes user input and evaluates it. User input can only be either “a” or “b”, otherwise an error occurs. I have been using this:
def checkResponse(resp):
#Make the incoming string trimmed & lowercase
respRaw = resp.strip()
respStr = respRaw.lower()
#Make sure only a or b were chosen
if respStr != "a" | respStr != "b":
return False
else:
return True
However, when I input a or b, I receive this: TypeError: unsupported operand type(s) for |: 'str' and 'str'
Is this the incorrect way to compare a string? Is there a built in function to do this like with Java? Thanks!
|is the bitwise or operator. You wantor. (You actually wantand.)You wrote:
Bitwise operators have high precedence (similar to other arithmetic operators), so this is equivalent to:
where the two
!=operations are chained comparison operators (x != y != zis equivalent tox != y and y != z). It’s meaningless to apply bitwise or to two strings.You meant to write:
You could also write, using chained operators:
Or, using the containment operator
in: