Python 3.4.4 How to verify if a string is only made of 0 and 1
<p>I'm doing a binary to decimal converter in python 3.4.4 and it's pretty much finished except for the fact that I would like to check that the binary number entered by the user is indeed a binary number (check if the string is only made of o and 1) but I'm unsure what to do.</p>

<p>here's the program:</p>

<pre><code>binary=input("Enter a binary number") 
bit=len(binary)
result=0
power=0
while bit&gt;0:
    result=result+int(binary[bit-1])*2**power
    bit=bit-1
    power=power+1
print(binary, " in decimal is equal to ", result, sep="")
</code></pre>

<p>hopefully someone can help me &lt;3</p>

<p>If you <em>must</em> avoid using <code>int(binary, 2)</code> and handle the exception, you could use the <a href="https://docs.python.org/2/library/functions.html#any" rel="nofollow"><code>all()</code> function</a> with a <a href="https://docs.python.org/2/tutorial/classes.html#generator-expressions" rel="nofollow">generator expression</a>:</p>

<pre><code>all(c in '01' for c in binary)
</code></pre>

<p><code>all()</code> with a generator expression will bail out early and return <code>False</code> when a non-binary digit is found.</p>

<p>If you are already looping over all characters <em>anyway</em> you could just raise an exception in your loop:</p>

<pre><code>binary=input("Enter a binary number") 
bit=len(binary)
result=0
power=0
try:
    while bit&gt;0:
        if binary[bit-1] not in '01':
            raise ValueError('Not a binary string: %s' % binary)
        result=result+int(binary[bit-1])*2**power
        bit=bit-1
        power=power+1
except ValueError:
    print('%s is not a binary string')
else:
    print(binary, " in decimal is equal to ", result, sep="")
</code></pre>

<p>Rather than use an index, your code could just loop over the reverse of the string, using numbers generated by <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate()</code></a> as the power:</p>

<pre><code>binary = input("Enter a binary number") 
result = 0
try:
    for power, bit in enumerate(reversed(binary)):
        if bit not in '01':
            raise ValueError('Not a binary string: %s' % binary)
        result += int(bit) * 2 ** power
except ValueError:
    print('%s is not a binary string')
else:
    print(binary, " in decimal is equal to ", result, sep="")
</code></pre>

python