Python Forum

Full Version: I've always wanted to write this but having problems
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I've wanted to write a program that converts an integer to it's binary equivalent. I'm getting an error saying Unbound Local Error. Local variable binary_string referenced before assignment. The last line in the while loop before the return statement is being flagged an error. I probably have other things wrong too if you see them please let me know.

I'm rather lost:
def main():
    x = int(input("Enter an integer: "))
    binary_string = ""
    binary_string = decimal_to_binary(x)
    
def decimal_to_binary(n): 
    
    while(n > 0):
        remainder = n % 2
        n = n / 2
        binary_string = str(remainder) + binary_string
        
    return binary_string

main()
The error is pretty clear: you try to use the variable binary_string on line 13, but it doesn't exist in that scope - it's only defined in the loop.
Another approach could be using divmod:

def to_binary(num):
  reminders = []
  while num:
      num, reminder = divmod(num, 2)
      reminders.append(reminder)
  return ''.join(str(x) for x in reversed(reminders),)
To test:

>>> to_binary(42)
'101010'
>>> int(to_binary(42), 2)
42