以下是一个根据条件返回长度的函数的示例代码:
def get_length(condition, string):
if condition:
return len(string)
else:
return 0
# 测试函数
print(get_length(True, "Hello World")) # 输出:11
print(get_length(False, "Hello World")) # 输出:0
在上面的代码中,get_length
函数接受两个参数:condition
和string
。它根据condition
的值来决定返回string
的长度还是返回0。如果condition
为True
,则返回string
的长度;否则返回0。
在示例中,我们通过调用get_length
函数来测试它的功能。第一个测试用例中,condition
为True
,所以返回的长度是字符串"Hello World"的长度,即11。第二个测试用例中,condition
为False
,所以返回的长度为0。
你可以根据自己的需求修改get_length
函数的条件和返回值。