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>I suppose checking the input string for correctness is best done with regular expressions. The code that would help you is the following:</p>

<pre><code>import re

binary = input("Enter a binary number") 
len_bin = len(binary)
result = 0
if re.search("^[0-1]+$", binary) is not None:
    for position in range(len_bin):
        result += int(binary[position]) * 2 ** (len_bin - position - 1)

    print(binary + " in decimal is equal to " + str(result))
else:
    print("The input is not a binary number")
</code></pre>

<p>The regular expression determines whether the binary number only contains zeros and ones. Also, I took the opportunity to shorten the code a bit, using <code>result += ...</code>, which is equal to <code>result = result + ...</code>.</p>

python