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)
0xCursor
2,2784 gold badges18 silver badges35 bronze badges
-
this is code for binary to decimal conversionrikeeeshi– rikeeeshi2018年09月01日 14:46:42 +00:00Commented Sep 1, 2018 at 14:46
-
1Post the error you get.Denziloe– Denziloe2018年09月01日 14:47:32 +00:00Commented Sep 1, 2018 at 14:47
1 Answer 1
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.
lang-py