Python 调用自身的函数只返回其调用的第一个结果

Python 调用自身的函数只返回其调用的第一个结果,python,return,call,Python,Return,Call,我有一个字符串s=“expenses>drinks”发送到函数。在该函数中,我应该使用raw\u input()添加新值,直到输入一个空字符串 这些输入中的每一个都应添加到初始字符串中。对于空字符串,函数必须返回包含所有先前添加的单词的字符串 我试图通过从函数本身调用函数来实现它,并将更改后的字符串传递给它,但它只返回第一个添加的单词。我还尝试使用避免从函数本身调用函数,而True:则为空字符串,如果为空字符串,则中断循环并返回值。但这些变体都不能正常工作 请解释一下我做错了什么,什么是做这件事

我有一个字符串
s=“expenses>drinks”
发送到函数。在该函数中,我应该使用
raw\u input()
添加新值,直到输入一个空字符串

这些输入中的每一个都应添加到初始字符串中。对于空字符串,函数必须返回包含所有先前添加的单词的字符串

我试图通过从函数本身调用函数来实现它,并将更改后的字符串传递给它,但它只返回第一个添加的单词。我还尝试使用
避免从函数本身调用函数,而True:
则为空字符串,如果为空字符串,则中断循环并返回值。但这些变体都不能正常工作

请解释一下我做错了什么,什么是做这件事的最疯狂的方式

代码如下:

#!/usr/bin/env python -tt
# -*- coding: utf-8 -*-

def create_sub_cat(parent):     
    print "creating subcat\n %s > " %(parent)
    conf=raw_input("type new subcat or press \"ENTER\" to save changes\n")
    if conf!="":
        parent+=" > "+conf
        create_sub_cat(parent)
    return parent

s="expences  > drinks"
print create_sub_cat(s)

您可以将
iter
与for循环一起使用,您不需要继续调用函数,iter将一个sentinel值作为其最后一个参数,它将继续循环,直到输入sentinel值:

def create_sub_cat(parent):
    print "creating subcat\n {} > ".format(parent)
    for conf in iter(lambda: raw_input("type new subcat or"
                                       " press \"ENTER\" to save changes\n"),""): # empty string for sentinel value
        parent += " > " + conf
    return parent
或者使用while True:

def create_sub_cat(parent):
    print "creating subcat\n {} > ".format(parent)
    while True:
        conf = raw_input("type new subcat or"
                                       " press \"ENTER\" to save changes\n")
        if not conf: # if user enters empty string break
            break
        parent +=" > " + conf # else keep concatenating
    return parent
代码不起作用的原因是,您不返回递归调用,因此只得到第一个值:

def create_sub_cat(parent):
    print "creating subcat\n %s > " %(parent)
    conf=raw_input("type new subcat or press \"ENTER\" to save changes\n")
    if conf!="":
        parent+=" > "+conf
        return create_sub_cat(parent) # return 
    return parent

当你递归调用函数时,你没有对返回值做任何事情。您既不能
返回它的结果,也不能以其他方式使用它。好的,谢谢。这些解决方案中哪一个更好?@SergiiArtele,我更喜欢
iter
方法,但归根结底,这取决于个人对iter和while的偏好。两者都优先于递归方法。如果我将输入转换为int,则浮点。。我会使用try/except,但只是获取输入,我更喜欢iter。@我认为,使用嵌套函数而不是lambda会使它更具可读性。您可以向helper函数添加适当的docstring。此外,一个简短的函数名将使sentinel更加明显。现在很难在lambda长线的末端找到一条新的路线。