Question

I'm new at python (2.7.3) and I'm trying to write a program that converts a given decimal number into a binary one. To that end, I wrote a function that takes the decimal number and an empty list, divides the number by 2 appends the rest to the list and repeats the function with the remaining quotient until the quotient is 0.

def convert_to_bin(dec_num,list):
    quo = dec_num/2 # val is the quotient when dividing by 2
    rest = dec_num%2 # rest is the rest when dividing by 2
    list.append(rest)
    if (quo==0):
        list.reverse()
        print list
        return list
    else:
        convert_to_bin(quo,list)
bin_list = [] # initialize list for binary entries
dec_num = 83 # decimal number that is to be converted into binary       
bin_list = convert_to_bin(dec_num,bin_list)
print bin_list

The function works all right so far, I just can't find a way to actually return the list after calling the function - instead I always get "None" as a return statement. What am I doing wrong? Any help would be greatly appreciated.

Was it helpful?

Solution

You forgot to return the result of the recursive call:

else:
    return convert_to_bin(quo,list)

A recursive call returns to the caller, not the top-level frame. So a convert_to_bin() function calling convert_to_bin() again was ignoring the return value from the nested call, instead then returning None as the end of function is reached.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top