Validating the value of several variables
<p><strong>What I am after:</strong> The user is allowed to input only 0 or 1 (for a total of 4 variables). If the user inputs for example 2, 1, 1, 0 it should throw an error saying <code>Only 0 and 1 allowed</code>.</p>

<p><strong>What I've tried so far:</strong></p>

<pre><code>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)
</code></pre>

<p><strong>Problem:</strong> When I use such a statement, I get either the result even when I input for example 5, or I get 'only 0 and 1 allowed' even though I wrote all 1 or 0.</p>

<hr>

<p>I found this which seemed to be what I was after, but it is still not working like I want it to:</p>

<pre><code>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')
</code></pre>

<p>This code basically gives me the same result as what I get with the first code sample.</p>

<p>This is due to the operator precedence in python. The <code>or</code> operator is of higher precedence than the <code>and</code> operator, the list looks like this:</p>

<ol>
<li><code>or</code></li>
<li><code>and</code></li>
<li><code>not</code></li>
<li><code>!=</code>, <code>==</code></li>
</ol>

<p>(Source: <a href="https://docs.python.org/3/reference/expressions.html#operator-precedence" rel="nofollow">https://docs.python.org/3/reference/expressions.html#operator-precedence</a>)</p>

<p>So, python interprets your expression like this (the brackets are to clarify what is going on):</p>

<pre><code>if (firstBinary != 0 or (firstBinary != 1 and secondBinary != 0 or (secondBinary != 1 and \
thirdBinary != 0 or (thirdBinary != 1 and forthBinary != 0 or (forthBinary != 1)))))
</code></pre>

<p>Which results in a different logic than what you want. There are 2 possible solutions to this, the first one is to add brackets to make the expression unambiguous. This is quite tedious and long-winded:</p>

<pre><code>if ((firstBinary != 0 or firstBinary != 1) and (secondBinary != 0 or secondBinary != 1) and \
(thirdBinary != 0 or thirdBinary != 1) and (forthBinary != 0 or forthBinary != 1))
</code></pre>

<p>The other approach is to use the in-built <code>all</code> function:</p>

<pre><code>vars = [firstBinary, secondBinary, thirdBinary, fourthBinary]
if not all(0 &lt;= x &lt;= 1 for x in vars):
    print("Only 0 or 1 allowed")
</code></pre>

python