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

How to return a value from a recursive Python function?(如何从递归 Python 函数中返回一个值?)
本文介绍了如何从递归 Python 函数中返回一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题似乎有点具体,对此我很抱歉,但这让我很困惑.我正在为自己编写一个密码生成器,它接受一个字符串(也就是网站的 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

这篇关于如何从递归 Python 函数中返回一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)