4

I have some code with an if-statement in it, and one of the conditions is a boolean. However, CodeSkulptor says "Line 36: TypeError: unsupported operand type(s) for BitAnd: 'bool' and 'number'". Please help if you can. This is what that piece of code looks like. (I just changed all the variable names and what the if-statement executes)

thing1 = True
thing2 = 3

if thing2 == 3 & thing1:
   print "hi"
4
  • Use and instead of &. One word of caution, use parentheses among the expressions that you want to evaluate. You can find unexpected results if you do not. Commented May 12, 2013 at 3:53
  • @Imagine: == has a higher precedence than and, so nothing will happen. Commented May 12, 2013 at 3:56
  • @Blender True, but to quote the zen of python: explicit is better than implicit. I'd rather add unnecessary yet clarifying parentheses than rely on an imperfect knowledge of operator precedence. Commented May 12, 2013 at 4:10
  • @ValekHalfHeart: I've rarely seen if (foo == 2) and bar, but it's personal preference to add them in if you feel that they make it clearer. Commented May 12, 2013 at 4:17

2 Answers 2

7

You want to use logical and (not the &, which is a bitwise AND operator in Python):

if thing2 == 3 and thing1:
   print "hi"

Because you have used &, the error has popped up, saying:

TypeError: unsupported operand type(s) for BitAnd: 'bool' and 'number'
                                           ^^^^^^
Sign up to request clarification or add additional context in comments.

Comments

4

& is the bitwise AND operator. You want to use the logical and instead:

if thing2 == 3 and thing1:
    print "hi"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.