0

Below is a Python program, that I have written, that converts decimal numbers to binary. However, I'm getting errors. Can anyone help?

def decimaltobin(n):

    (ls,count,i)=([],0,0)
    while(n>0):
        ls[i]=n%2
        n=n/2
        i=i+1
    while(i>0):
        print(ls[i])
        i=i-1

decimaltobin(8)
2
  • this is code for binary to decimal conversion Commented Sep 1, 2018 at 14:46
  • 1
    Post the error you get. Commented Sep 1, 2018 at 14:47

1 Answer 1

2

You declare ls as an empty list, which means you cannot set element ls[i] as a value since ls[i] does not exist. For your code, you should add the new value to the list with, for example, ls.append(n%2). You also need to decrement the i to i-1 after your iterations in the first while loop to correctly call ls[i] in the second while loop.

def decimaltobin(n):
    (ls,count,i)=([],0,0)
    while(n>0):
        ls.append(n%2)
        n=n//2
        i=i+1
    i=i-1
    while(i>=0):
        print(ls[i])
        i=i-1
Sign up to request clarification or add additional context in comments.

3 Comments

Surely you mean n=n//2 in line 5, or it will break :)
I assumed n was an integer which would return the same as using //
Well, it broke for me on Python 3.6.5 under windows 10. Think it may react differently in different environments...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.