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

编程入门 行业动态 更新时间:2024-10-25 09:28:51
本文介绍了如何从递归Python函数返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这个问题似乎有点特殊,为此我很抱歉,但它让我难倒了。我为自己写了一个密码生成器,它需要一个字符串(也就是网站的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函数返回值?

本文发布于:2023-10-11 22:28:27,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   函数   返回值   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!