|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
动动手的第0题 十进制转二进制
- def Dec2Bin(dec):
- result = ''
-
- if dec:
- result = Dec2Bin(dec//2)
- return result + str(dec%2)
- else:
- return result
- print(Dec2Bin(62))
复制代码
第一题 get_digits(12345)实现[1,2,3,4,5]
- result = []
- def get_digits(n):
- if n > 0:
- result.insert(0, n%10)
- get_digits(n//10)
- get_digits(12345)
- print(result)
复制代码
第0题的 result定义在函数之内(每次递归的时候不就置为''了吗),第1题的 result定义在函数之外,两道题明明很相似为什么一个要定义在函数内另一个要定义在函数外???
如果将第0题的result定义在函数外又会报错 local variable 'result' referenced before assignment
如果将第1题的result定义在函数内也不会得到想要的结果
1.第0题如果result定义在函数之外,当dec==0的时候直接return result,而此时定义的函数中也存在result所以暂时回吧外面定义的result封闭起来,所以此时返回的result就没有定义了,那肯定是要报错的
如果想把result定义在函数外就需要将result换一个定义字符如str1,然后函数内部返回else: return str1,这样函数内部没有定义str1就不会封闭起外部的str1,就可以使用了
第一题如果把result定义在函数里面的话,因为函数没有返回值,跳出函数,系统就会吧局部变量result杀死,所以得不到想要的结果
|
|