简体   繁体   中英

Python program for converting decimal to binary

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM