在append()和reverse()之后返回列表

2024-09-24 22:30:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python(2.7.3)的新手,我正试图编写一个程序,将给定的十进制数转换为二进制数。 为此,我编写了一个函数,它接受十进制数和一个空列表,将数字除以2,然后将其余的附加到列表中,并用剩余的商重复该函数,直到商为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

到目前为止,这个函数还可以正常工作,只是我无法找到一种方法在调用函数之后返回列表—相反,我总是得到“None”作为返回语句。 我做错什么了?任何帮助都将不胜感激。在


Tags: theto函数restconvert列表bybin
1条回答
网友
1楼 · 发布于 2024-09-24 22:30:42

您忘记返回递归调用的结果:

else:
    return convert_to_bin(quo,list)

递归调用返回到调用方,而不是顶层框架。因此,再次调用convert_to_bin()convert_to_bin()函数忽略了嵌套调用的返回值,而是在函数结束时返回None。在

相关问题 更多 >