2013-05-12 98 views
4

我有一些if語句的代碼,其中一個條件是布爾值。然而,CodeSkulptor說:「第36行:TypeError:BitAnd不支持的操作數類型:'bool'和'number'」。如果可以的話請幫忙。這是這段代碼的樣子。 (我只是改變了所有的變量名和if語句執行的)在Python中的If語句中使用布爾值

thing1 = True 
thing2 = 3 

if thing2 == 3 & thing1: 
    print "hi" 
+0

使用和代替&。謹慎的一句話,在要評估的表達式中使用括號。如果不這樣做,你可以找到意想不到的結果。 – James 2013-05-12 03:53:49

+0

@Imagine:'=='比'和'具有更高的優先級,所以什麼都不會發生。 – Blender 2013-05-12 03:56:19

+0

@Blender真的,但要引用python的禪意:顯式比隱式更好。我寧願添加不必要的但明確的括號,而不是依賴於運算符優先級的不完善知識。 – ApproachingDarknessFish 2013-05-12 04:10:01

回答

6

你想使用邏輯and(不是&,這是Python中的位AND運算符):

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

因爲你已經使用&,錯誤已經彈出,說:

TypeError: unsupported operand type(s) for BitAnd: 'bool' and 'number' 
              ^^^^^^ 
3

&是按位與運算。你想使用邏輯and代替:

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