如何从递归 Python 函数中返回一个值?

2022-01-19 00:00:00 python function 递归 return

问题描述

这个问题似乎有点具体,对此我很抱歉,但这让我很困惑.我正在为自己编写一个密码生成器,它接受一个字符串(也就是网站的 URL)并将其处理成一个安全密码,该密码不能根据网站名称回溯.

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())

我希望'nums' 输出两次,因为我在 else 块中打印它并稍后打印返回.但是,如果它确实通过了递归循环,则从 else 块打印nums",并且该函数返回None".如果 if len(nums) <num_length 第一次为假,然后返回正确的值.

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.

如果我验证它返回的对象实际上不是之前的行None",为什么它会返回None"?

Why would it return 'None', if I verified that the object it is returning is not in fact 'None' the line before?

我对 Python 有点陌生,他们处理递归的方式不同吗?

I'm a little new to Python, do they handle recursions differently?

感谢您的宝贵时间

问题已解决.忘记了递归调用的返回语句.谢谢:D

Problem fixed. Forgot a return statement on the recursive call. Thanks :D


解决方案

我认为您在嵌套的 get_number 之前缺少一个 return.所以,它正在执行并返回,但你没有对递归值做任何事情.

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

相关文章