2016-09-17 26 views
3

我在之後:用戶只能輸入0或1(總共4個變量)。如果用戶輸入例如2,1,1,0,則應該拋出一個錯誤,說Only 0 and 1 allowed驗證多個變量的值

我試過到目前爲止:

if (firstBinary != 0 or firstBinary != 1 and secondBinary != 0 
     or secondBinary != 1 and thirdBinary != 0 or thirdBinary != 1 
     and forthBinary != 0 or forthBinary != 1): 
    print('Only 0 and 1 allowed') 
else: 
    print('binary to base 10: result) 

問題:當我使用這樣的表述,我得到任何結果,甚至當我例如5個輸入,或者我得到「只0和1的允許」即使我寫的所有1或0


我發現這裏面似乎是什麼我之後,但它仍然沒有工作一樣,我希望它:

if 0 in {firstBinary, secondBinary, thirdBinary, forthBinary} or 1 in \ 
    {firstBinary, secondBinary, thirdBinary, forthBinary}: 
    print("Your result for binary to Base 10: ", allBinaries) 
else: 
    print('Only 0 and 1 allowed') 

這段代碼基本上給了我與第一個代碼示例相同的結果。

+0

確定'打印(「您的結果爲二進制基10:「,allBinaries)'不應該縮進? –

+0

我很抱歉,你是什麼意思縮進(壞英語)?變量allbinaries只是將a,b,c,d與8,4,2,1相乘並將它們相加。如果這是什麼 – SunnlightBro

+0

我的意思是在行之前加上空格,以便它在if塊 –

回答

6

使用any

v1, v2, v3, v4 = 0, 1, 1, 2 

if any(x not in [0, 1] for x in [v1, v2, v3, v4]): 
    print "bad" 
當然

,如果你使用的列表就會看起來更棒

inputs = [1, 1, 0 , 2] 

if any(x not in [0, 1] for x in inputs): 
    print "bad" 
+0

謝謝,簡單易懂! – SunnlightBro

1

我把它分成兩個部分,你想解決方法:

是否有特定的輸入有效? 所有的輸入是否合在一起有效?

>>> okay = [0,1,1,0] 
>>> bad = [0,1,2,3] 

>>> def validateBit(b): 
... return b in (0, 1) 

>>> def checkInput(vals): 
... return all(validateBit(b) for b in vals) 
... 
>>> checkInput(okay) 
True 
>>> checkInput(bad) 
False 
>>> 
+0

總的來說,我認爲這個答案顯示出比所有單行者更好的風格,因爲它將每個操作分爲正交函數。快速瀏覽一下它確實很容易理解它的功能。 (第一次是正確的 - 許多其他答案必須經過編輯才能得到正確的代碼!) – wjl

3

這是由於Python中的運算符優先級。該or運營商比and運營商更高的優先級,列表如下:

  1. or
  2. and
  3. not
  4. !===

(來源:https://docs.python.org/3/reference/expressions.html#operator-precedence

所以,蟒蛇解釋你的表情像這樣(括號內是澄清這是怎麼回事):

if (firstBinary != 0 or (firstBinary != 1 and secondBinary != 0 or (secondBinary != 1 and \ 
thirdBinary != 0 or (thirdBinary != 1 and forthBinary != 0 or (forthBinary != 1))))) 

這會導致不同的邏輯比你想要的東西。有兩種可能的解決方案,第一種是添加括號以使表達式無歧義。這是相當繁瑣和囉嗦:

if ((firstBinary != 0 or firstBinary != 1) and (secondBinary != 0 or secondBinary != 1) and \ 
(thirdBinary != 0 or thirdBinary != 1) and (forthBinary != 0 or forthBinary != 1)) 

另一種方法是使用內置all功能:

vars = [firstBinary, secondBinary, thirdBinary, fourthBinary] 
if not all(0 <= x <= 1 for x in vars): 
    print("Only 0 or 1 allowed") 
0
values = [firstBinary, secondBinary, thirdBinary] 
if set(values) - set([0, 1]): 
    print "Only 0 or 1, please"