MyPoorBrain MyPoorBrain - 2 months ago 5
Python Question

Convert from decimal to Binary function

I tried creating a function to convert to binary the long way but i keep getting a very basic error that i can't seem to figure out. Would appreciate an extra pair of eyes.

def convert_to_binary(n):

if (-1.0 < n < 256.0):
number_list = []
while (n != 0):
rem = n % 2
number_list.append(rem)
n = n // 2

new_list = number_list[::-1]
print("".join(str(x) for x in new_list))

else:
print("Invalid input")


the error i keep getting is:

File "", line 13
else :
^
SyntaxError: invalid syntax


I'd really appreciate any feedback. Thanks

Answer
def convert_to_binary(n):
   if (-1.0 < n < 256.0):
      print '{0:b}'.format(n)
   else:
      print("Invalid input")
Comments