Python 3.4.4. How to check that a string consists of only 0 and 1

I am making a binary decimal converter in python 3.4.4 and it is pretty much complete, except for the fact that I would like to check that the binary number entered by the user is really a binary number (check if the string is made only from o and 1), but I'm not sure what to do.

here is the program:

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

hope someone can help me <3

+4
source share
7 answers

Follow the EAFP approach , try converting it to decimal with int()and process ValueError:

try:
    int(binary, 2)
    is_binary = True
except ValueError:
    is_binary = False
+6
source

int(binary, 2) , all() :

all(c in '01' for c in binary)

all() False, .

, :

binary=input("Enter a binary number") 
bit=len(binary)
result=0
power=0
try:
    while bit>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="")

, , , , enumerate()

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="")
+3

all()

 all(x in '10' for x in binary_string) 
+2

all(x in "01" for x in binary).

+1

2.7.9, 3.4.4:

import re

binary = raw_input("enter binary number")
if re.match("^[01]*$", binary):
    print "ok"
0

, "0" "1" .

 binary.count('0') + binary.count('1') == len(binary)
0

, . , , :

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")

A regular expression determines whether a binary number contains only zeros and ones. In addition, I took the opportunity to slightly reduce the code using result += ..., which is equal result = result + ....

0
source

Source: https://habr.com/ru/post/1654165/


All Articles