Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.4.4 How to verify if a string is only made of 0 and 1

Tags:

python

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.

here's 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="")

hopefully someone can help me <3

like image 525
Jabrilgalien Avatar asked Dec 14 '22 03:12

Jabrilgalien


2 Answers

Follow the EAFP approach, try to convert it to decimal via int() and handle the ValueError:

try:
    int(binary, 2)
    is_binary = True
except ValueError:
    is_binary = False
like image 173
alecxe Avatar answered Feb 23 '23 09:02

alecxe


If you must avoid using int(binary, 2) and handle the exception, you could use the all() function with a generator expression:

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

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

If you are already looping over all characters anyway you could just raise an exception in your loop:

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

Rather than use an index, your code could just loop over the reverse of the string, using numbers generated by enumerate() as the power:

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="")
like image 38
Martijn Pieters Avatar answered Feb 23 '23 11:02

Martijn Pieters