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

2023-09-02Python开发问题
2

本文介绍了如何从递归 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 函数中返回一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11