python recursive function returning none instead of string

Question:

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

Asked By: Romby Soft

||

Answers:

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 "nnStopping 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 "nnStopping 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
Answered By: Akshay Agrawal

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.

Answered By: user1741851
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.