|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
def Dec2Bin(dec):
result = ''
if dec:
result = Dec2Bin(dec//2) 这个里面result是否有被赋值,在这里result的作用是什么,我发现这个位置的result的值始终是“”空字符
return result + str(dec%2)
else:
return result
print(Dec2Bin(62))
谢谢那位老师能帮我看看。
本帖最后由 Stubborn 于 2021-2-20 21:06 编辑
你要想明白,递归调用的时候,你一层一层的调用函数(调用的时候是没有返回结果的),等到递归出口的时候,才开始一层一层的往回传结果。 就是说if里面result的复制要等到else return result,返回这个result的时候,才能接受到结果
- def Dec2Bin(dec):
- """
- 已dec=10举例说明。
- 第一次调用:if 10: result = Dec2Bin(5) -->这里继续调用函数,result还没有获得函数的返回结果
- 下面的return result + str(dec % 2)不会执行
- 第二次调用: if 5: result = Dec2Bin(2)
- 第三次调用: if 2: result = Dec2Bin(1)
- 第四次调用: if 1: result = Dec2Bin(0)
- 运行Dec2Bin(0)这个函数的时候,返回result = '' 注意这个是返给第四次调用的
- 现在第四次调用收到结果了,开始返回结果:return result + str(1 % 2)-> '' + '1',返给第三次调用的
- 第三次调用收到结果:result = "1", 继续返回结果:return result + str(2 % 2)-> '1' + '0',返给第二次调用的
- 第二次调用收到结果:result = "10",继续返回结果:return result + str(5 % 2)-> '10' + '1',返给第一次次调用的
- 第一次调用收到结果:result = "101",继续返回结果:return result + str(10 % 2)-> '101' + '0'
- 最终返回‘1010’
- """
- result = ''
- if dec:
- result = Dec2Bin(dec // 2)
- return result + str(dec % 2)
- else:
- return result
复制代码
|
|