这个问题似乎有点特殊,为此我很抱歉,但它让我难倒了。我为自己写了一个密码生成器,它需要一个字符串(也就是网站的URL)并将其处理成一个安全的密码,该密码不能根据网站的名称回溯。
在部分代码中,我创建了一个如下所示的递归函数:
def get_number(n = 0,nums =''):在范围内(0,len(url)): #both n和nums被更改如果len(nums)< num_length: get_number(n,nums) else: print(nums) return(nums)...
print(get_number())我希望'nums'输出两次,因为我在else块中打印并稍后打印返回值。但是,如果它通过递归循环,则从else块打印'num',函数返回'None'。如果 if len(nums)< num_length 第一次为false,则返回正确的值。
为什么它返回'None',如果我验证了该对象它是返回不是事实上'无'之前的行?
我对Python有点新,他们处理递归是不同的?
感谢您的时间
编辑: 问题修复了。忘记了递归调用的返回声明。感谢:D
解决方案我想你以前缺少 return 嵌套 get_number 。因此,它正在执行并返回,但您对递归值没有做任何处理。
def get_number(n = 0, (0,len(url)): #both n和nums被更改如果len(nums)< nums =''): num_length:返回get_number(n,nums) print(nums)返回nums
This question seems a bit specific, and for that I'm sorry, but it has me stumped. I'm writing myself a password generator, one that takes a string (aka the URL of a website) and processes it into a secure password that can't be backtracked based on the name of the website.
In part of the code, I created a recursive function that looks like this:
def get_number(n = 0, nums = ''): for i in range(0, len(url)): #both n and nums are changed if len(nums) < num_length: get_number(n, nums) else: print(nums) return(nums)...
print(get_number())I would expect 'nums' to output twice, since I print it in the else block and print the return later on. But, if it does go through a recursive loop, 'nums' is printed from the else block and the function returns 'None'. If if len(nums) < num_length is false the first time, then it returns the proper value.
Why would it return 'None', if I verified that the object it is returning is not in fact 'None' the line before?
I'm a little new to Python, do they handle recursions differently?
Thank you for your time
Edit:
Problem fixed. Forgot a return statement on the recursive call. Thanks :D
解决方案I think you're missing a return before the nested get_number. So, it's executing and returning, but you aren't doing anything with the recursed value.
def get_number(n = 0, nums = ''): for i in range(0, len(url)): #both n and nums are changed if len(nums) < num_length: return get_number(n, nums) print(nums) return nums
更多推荐
如何从递归Python函数返回值?
发布评论