0

I am very new to Python and coding in general. For my school assignment I have to create a program that converts from binary to decimal, but first I need also to check if input is binary. Basically - I have separate code that check if input is correct and another one that converts. Any advice on how to combine those two? This is my first task ever and I really got stuck. Please note that I am not allowed to use any built-in functions. Appreciate any advice about what mistake do I do here?

my_binary = input("Enter binary number: ")
decimal = 0
index = 0
exponent = len(my_binary) - 1

def b_to_d(my_binary):
    for character in my_binary:
        if character != '0' and character != '1':
            print ('Number is not binary!')
            return False
    print ('Number is binary')
    return True
b_to_d(str(my_binary))

while True and index != len(my_binary):
    decimal += int(my_binary[index]) * 2**exponent
    index += 1
    exponent -= 1
print(decimal)
new_neri
  • 15
  • 5

2 Answers2

1

Your function is correct but you are proceeding to calculate the decimal number without checking whether the number is binary or not. Only convert to decimal if the number is binary.

my_binary = input("Enter binary number: ")
decimal = 0
index = 0
exponent = len(my_binary) - 1

def b_to_d(my_binary):
    for character in my_binary:
        if character != '0' and character != '1':
            print ('Number is not binary!')
            return False
    print ('Number is binary')
    return True

is_binary = b_to_d(str(my_binary))

if is_binary:
    while index != len(my_binary):
        decimal += int(my_binary[index]) * 2**exponent
        index += 1
        exponent -= 1
    print(decimal)
HariUserX
  • 1,341
  • 1
  • 9
  • 17
1

HariUserX explains the error in your code. Although, I would add as a sidenote that your code can be significantly shortened.

my_binary = input("Enter binary number: ")
try:
    decimal = int(my_binary, 2)
except ValueError:
    print('Number is not binary!')

The above uses the "ask forgiveness not permission" principle. Try to convert the number in binary and check if it fails, Python is built to be inherently better with this approach.

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
  • As I understand this is more pythonic way. Thank you! – new_neri Mar 17 '19 at 14:06
  • @new_neri Yes, the thing is Python already internally checks the value of `my_binary` when you attempt to cast it. So checking it yourself simply adds unnecessary work. In fact, since Python is dynamically typed, it does *a lot* of type and value checks at runtime and that is why you should leave them to the interpreter and just catch the exception if it fails. – Olivier Melançon Mar 17 '19 at 15:11