下面的python函数使用print函数打印值,但如果返回字符串值则返回none。任何人都可以帮助我如何从下面的函数返回一个字符串值。
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
但返回:
无
答案 0 :(得分:0)
尝试以下代码。
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))
第二个变化:
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))
输出:
> 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
答案 1 :(得分:0)
您需要在函数内部使用return create_csv_name(comm, index=index)
。否则,您不会在第一次调用函数时返回任何内容。这也解释了您的None
返回值。
递归是一个需要敏锐观察的主题。并且需要一些时间来熟悉并应用于实际应用中。