2

I'm writing a password generator, one that takes a string (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; does it handle recursions differently?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Joe Finn
  • 71
  • 1
  • 7

1 Answers1

8

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
Karin
  • 8,404
  • 25
  • 34
  • 2
    The point is that you have to return the called function. Some languages allow you to simply return the value on the last called function. I should say some compilers of some languages. C++ for Win32 is one that works this way. The call stack looks to the last recursive call to return the value, but not in python – David Kamer Jul 05 '18 at 00:36