问题
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
回答1:
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
来源:https://stackoverflow.com/questions/38882826/how-to-return-a-value-from-a-recursive-python-function