2

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!

asked Jul 16, 2012 at 16:58
3
  • 1
    Where is the if that corresponds to your elif? Commented Jul 16, 2012 at 17:00
  • I cut it out to reduce some unnecessary code, but I'll fix...thanks! Commented Jul 16, 2012 at 17:01
  • 1
    In addition to the points about operators in the answers below, you can chain string methods, so return resp.strip().lower() in ('a', 'b') can be the entire function. Commented Jul 16, 2012 at 17:23

2 Answers 2

7

| is the bitwise or operator. You want or. (You actually want and.)

You wrote:

if respStr != "a" | respStr != "b":

Bitwise operators have high precedence (similar to other arithmetic operators), so this is equivalent to:

if respStr != ("a" | respStr) != "b":

where the two != operations are chained comparison operators (x != y != z is equivalent to x != y and y != z). It's meaningless to apply bitwise or to two strings.

You meant to write:

if respStr != "a" and respStr != "b":

You could also write, using chained operators:

if "a" != respStr != "b":

Or, using the containment operator in:

if respStr not in ("a", "b"):
answered Jul 16, 2012 at 17:00
Sign up to request clarification or add additional context in comments.

Comments

5

What you want is respStr != 'a' and respStr != 'b' (or is the boolean operator, | the bitwise one - however, you need and for your check).

However you can write the condition in an even nicer way without repeating the variable name:

return respStr in ('a', 'b')

This will return True if respStr is a or b and False otherwise.

answered Jul 16, 2012 at 17:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.