python recursive function returning none instead of string

和自甴很熟 提交于 2019-12-24 19:28:48

问题


The below python function prints value using print function but is returning none if made to return string value. can anyone help me on how to return a string value from this below function.

csv_full_list = ['mycsv_0', 'mycsv_1']


def create_csv_name(comm, index):
    global csv_full_list
    if comm + '_' + str(index) in csv_full_list:
        index += 1 # increment index by 1
        create_csv_name(comm, index=index)
    else:
        print '%s_%i' % (comm, index)
        return '%s_%i' % (comm, index)


print(create_csv_name('mycsv', 0))

out put expected :

mycsv_2

but returns:

None


回答1:


Try out the following code.

csv_full_list = ['mycsv_0', 'mycsv_1']


def create_csv_name(comm, index):
    global csv_full_list
    result = True
    print "ATTEMPT: COMM: {}, INDEX: {}".format(comm, index)

    while result:
        if comm + '_' + str(index) not in csv_full_list:
            result = False

        else:
            index += 1 # increment index by 1
            #print "--> Found COMM: {}, INDEX: {}".format(comm, index)
            create_csv_name(comm, index=index)

    if not result:
        return "\n\nStopping at >> COMM: {}, INDEX: {}".format(comm, index)

# Call the def
print(create_csv_name('mycsv', 0))

2nd variation:

csv_full_list = ['mycsv_0', 'mycsv_1']


def create_csv_name(comm, index):
    global csv_full_list
    result = True
    print "ATTEMPT: COMM: {}, INDEX: {}".format(comm, index)

    if comm + '_' + str(index) not in csv_full_list:
        return "\n\nStopping at >> COMM: {}, INDEX: {}".format(comm, index)
    else:
        index += 1 # increment index by 1
        return create_csv_name(comm, index=index)

print(create_csv_name('mycsv', 0))

output:

> python.exe .\sample.py
ATTEMPT: COMM: mycsv, INDEX: 0
ATTEMPT: COMM: mycsv, INDEX: 1
ATTEMPT: COMM: mycsv, INDEX: 2
ATTEMPT: COMM: mycsv, INDEX: 2


Stopping at >> COMM: mycsv, INDEX: 2



回答2:


You need to use return create_csv_name(comm, index=index) inside the function. Otherwise, you are not returning anything from the first call to the function. That also explains your None return value.

Recursion is a topic that requires keen observation. And takes some time to get familiar and apply in real application.



来源:https://stackoverflow.com/questions/47385933/python-recursive-function-returning-none-instead-of-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!