0

Am trying to make a simple program to convert binary number to decimal number. I'd like to first write a condtion whether to check the given number is a binary or not.
How do i do that?
Except that, the program works normally without any errors but am afraid when a non binary number is given, it still does the job.

Input

print("Binary to Decimal")

bin = input("Give a binary number : ")
bin = [int(i) for i in bin]

powers = [i for i in range(len(bin)-1,-1,-1)]

for i in range(len(bin)):
  bin[i] = bin[i] * 2**(powers[i])
decimal = sum(bin)
print("The corresponding Decimal digit is : %d"%(decimal))



Output

Binary to Decimal
Give a binary number : 101
The correspnding Decimal digit is : 5

Also if u find any corrections or want to make any suggestions, please feel free to suggest me below.

Aditya Nikhil
  • 351
  • 1
  • 3
  • 10

3 Answers3

0

You can check that if the string contains any other number rather than 0's and 1's then it is not a binary number.

ClassHacker
  • 394
  • 3
  • 11
0

Try pythonic way is not to test, but to try the conversion and catch the exception if the input is bad. This is the Easier to ask for forgiveness than permission prinicple:

b = input("Give a binary number : ")
try:
    print(int(b, 2))
except ValueError:
    print("not binary")

If you still want to check an easy test is to use all():

if all(n in ('1','0') for n in b):
   # it's all 1's and 0's
Mark
  • 90,562
  • 7
  • 108
  • 148
0

you can check with regular expression

import re

if re.match("^[01]+$", '011001'):
   //then proceed
else:
   //do something for non-binary
Shantanu Nath
  • 363
  • 3
  • 13