Python Forum
I've always wanted to write this but having problems
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I've always wanted to write this but having problems
#1
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()
Reply
#2
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.
Reply
#3
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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Upgrading from 2 to 3 and having file write problems KenHorse 2 1,522 May-08-2022, 09:47 PM
Last Post: KenHorse

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020